代码之家  ›  专栏  ›  技术社区  ›  HelloWorld1

根据不同的行检索数据

  •  0
  • HelloWorld1  · 技术社区  · 8 年前

    今天的数据

    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 回复  |  直到 8 年前
        1
  •  0
  •   Yogesh Sharma    8 年前

    你可以使用 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;
    

    但是,您也可以将其重新表示为via 窗口 功能:

    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;