SQL:计算开始和结束日期(从结束到开始)

时间:2016-10-12 14:00:15

标签: sql sql-server

我使用Microsoft SQL Server管理系统。 我在这里有这张桌子:

enter image description here

我想从下一行计算(减号)'开始'与前一个'结束'。就像在标记的图片中一样。

2016-01-07 02:24:37.357 - 2016-01-07 02:24:25.170 = 0,000138889


started                   ended
2016-01-04 22:40:35.930   2016-01-05 02:01:36.500
2016-01-06 23:32:27.163   2016-01-07 02:24:25.170
2016-01-07 02:24:37.357   2016-01-07 02:57:04.010
2016-01-07 03:03:12.300   2016-01-07 22:41:55.473
2016-01-07 22:42:05.043   2016-01-07 22:55:07.947
2016-01-07 22:55:16.570   2016-01-08 00:23:08.263
2016-01-08 00:34:35.297   2016-01-08 05:32:54.967

3 个答案:

答案 0 :(得分:2)

您可以使用lag获取前一行的结束列并将其用于减法。

select *, 
datediff(second,lag(ended) over(partition by status order by started),started) as diff_column
from tablename

答案 1 :(得分:0)

如果你有SQL Server 2012或更新版本,对于这个,你可以使用LEAD和LAG函数,否则你需要在光标周围嵌入这个逻辑。

答案 2 :(得分:0)

 private void btnGo_Click(object sender, EventArgs e)
    {

        Random random = new Random();

        listBox1.Items.Clear();
        listBox2.Items.Clear();


        for (int i = 0; i < 10; i++)
        {

            int nummer = random.Next(20);
            int nummer2 = random.Next(20);
            listBox1.Items.Add(nummer);
            listBox2.Items.Add(nummer2);
        }




        if (addListbox1() > addListbox2())
        {
            textBox1.Text = "Listbox1 heeft de hoogste waarde namelijk " + Convert.ToString(addListbox1());
            listBox1.BackColor = Color.Green;
            listBox2.BackColor = Color.Red;


        }

        else
        {

            textBox1.Text = "Listbox2 heeft de hoogste waarde namelijk " + Convert.ToString(addListbox2());
            listBox1.BackColor = Color.Red;
            listBox2.BackColor = Color.Green;


        }



    }
    private int addListbox1()
    {
        int listbox1total = 0;

        for (int k = 0; k < listBox1.Items.Count;)
        {
            listbox1total += Convert.ToInt32(listBox1.Items[k++]);
        }
        return listbox1total;
    }

    private int addListbox2()
    {
        int listbox2total = 0;
        int k = 0;

        while(k < listBox2.Items.Count)
        {
            listbox2total += Convert.ToInt32(listBox1.Items[k++]);

        }
        return listbox2total;
    }