查询分组数据

时间:2015-11-11 13:32:42

标签: sql sql-server tsql

我有桌子:

id | Name | Nick | Points | Date
1  | John |Batman| 123    |2015-01-01
2  | John |Batman| 128    |2015-02-23
3  | John |Batman| 123    |2015-03-30
4  | John |Batman| 123    |2015-04-21
5  | John |Batman| 134    |2015-06-01
6  | John |Batman| 128    |2015-06-12
7  | John |Batman| 128    |2015-07-09
8  | John |Batman| 178    |2015-08-11

我想要输出:

Name | Nick | Points 
John |Batman| 123    
John |Batman| 128    
John |Batman| 123    
John |Batman| 134    
John |Batman| 128    
John |Batman| 178    

当我查询时:

Select Name, Nick, Points
from table
group by Name, Nick, Points

我有输出:

Name | Nick | Points 
John |Batman| 123    
John |Batman| 128    
John |Batman| 134    
John |Batman| 178    

我正在使用MSSQL2012(tsql)。

1 个答案:

答案 0 :(得分:0)

看起来你想要将点序列保持在一起。您可以使用行号的差异(或使用lag()

来执行此操作
select name, nick, points, min(date), max(date)
from (select t.*,
             (row_number() over (partition by name, nick order by date) -
              row_number() over (partition by name, nick, points order by date)
             ) as grp
      from table t
     ) t
group by name, nick, points, grp;

对于不包含日期的输出,另一种方法只使用lag()

select t.*
from (select t.*,
             lag(points) over (partition by name, nick order by date) as prev_points
      from table t
     ) t
where prev_points is null or prev_points <> points;