根据不同的行检索数据

时间:2018-06-19 15:59:28

标签: sql sql-server

今天使用表中的数据

ID  Datetime                   Status            Count1  Count2   RNdata
1   2018-01-31 15:30:05.190    Done reading      0       0        1
1   2018-01-31 15:30:05.190    Cancel            1       0        2
1   2018-01-31 15:30:05.190    Not started yet   0       1        3
1   2018-01-31 15:30:05.190    Almost            0       0        4

5   2018-02-06 15:30:07.583    Almost            0       0        1 
5   2018-02-06 15:30:07.583    Cancel            1       0        2

8   2018-01-22 15:30:29.747    Not started yet   0        1       1
8   2018-01-22 15:30:29.747    Cancel            1        0       2
8   2018-01-22 15:30:29.747    Done reading      0        0       3
8   2018-01-22 15:30:29.747    Almost            0        0       4

上面是一个示例,实际上,它是很多具有不同数据的数据行。 唯一的结构数据是RNDATA列

目标:
要求的结果如下。

ID  Datetime                   Status            Count1  Count2   RNdata
1   2018-01-31 15:30:05.190    Done reading      1        1       1
5   2018-02-06 15:30:07.583    Almost            1        0       1 
8   2018-01-22 15:30:29.747    Not started yet   1        1       1

我试图解决,但失败了:(

谢谢!

1 个答案:

答案 0 :(得分:0)

您可以使用apply

select t.id, t.datetime, tt.Status, 
       sum(Count1) as Count1, sum(Count2) as Count2, min(rndata) as rndata
from table t cross apply (
     select top 1 t1.Status
     from table t1
     where t1.id = t.id
     order by t1.rndata
   ) tt
group by t.id, t.datetime;

但是,您也可以通过 window 函数重新表达它:

select distinct id, datetime, 
      first_value(Status) over (partition by id order by rndata) as Status,
      sum(count1) over (partition by id) as count1,
      sum(count2) over (partition by id) as count2,
      min(rndata) over (partition by id) as rndata
from table t;