SQL组按数据

时间:2016-08-19 10:32:32

标签: sql tsql

我想按客户分组日期并为2个单独的值生成计数列(Flag = Y和Flag = N)。输入表如下所示:

Customer  Date   Flag
------- ------- -----
001      201201  Y
001      201202  Y
001      201203  Y
001      201204  N
001      201205  N
001      201206  Y
001      201207  Y
001      201208  Y
001      201209  N
002      201201  N
002      201202  Y
002      201203  Y
002      201205  N

输出应如下所示:

Customer MinDate  MaxDate Count_Y
-------  ------  -------  -------
001      201201   201203     3   
001      201206   201208     3      
002      201202   201203     2   

如何编写SQL查询?任何形式的帮助表示赞赏!谢谢!

1 个答案:

答案 0 :(得分:2)

过滤掉子句的位置,这样您只会获得用于分组的过滤项目

select 
customer,
min(date) as mindate,
max(date) as maxdate,
sum(case when flag='y' then 1 else 0 end ) count_y
from
table where flag='y'
group by
customer

根据Tanner评论更新:
由于min和max在你的约会上不会工作,我建议在下面..

;with cte
as
(
select *,date+'01' as newdate--now this is a valid date *yyyymmdd*
from cte
)
 select 
    customer,
    min(newdate) as mindate,
    max(newdate) as maxdate,
    sum(case when flag='y' then 1 else 0 end ) count_y
    from
    table where flag='y'
    group by
    customer