2016-08-19 96 views
0

我想按客户分组&日期并生成2个单独值(Flag = Y和Flag = N)的计数列。输入表看起来是这样的:SQL Group by data

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查询?任何形式的帮助表示赞赏!谢谢!

回答

2

过滤掉where子句,所以你将只能得到过滤项分组

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 

更新按照唐纳的评论:
以来的最小值和最大值不会在你的约会工作,我建议以下..

;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 
+1

@Tanner:谢谢,我没有看到日期。现在更新 – TheGameiswar