带有count和case语句的SQL查询

前端之家收集整理的这篇文章主要介绍了带有count和case语句的SQL查询前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要找到有多少人在60天内提交(fil_dt)他们的纳税申报表,120天内,180天内,提交期限结束日期(fpe)的180天,3年不同(2006年,2007年,2008年)

以下声明将给我所有年份
我需要每年和每种可能性的计数..
无论如何,我可以做2个查询吗?

SELECT YEAR(A.FPE) AS "YEAR",CASE                                              
  WHEN DAYS(A.FIL_DT) - DAYS(A.FPE) < 60 THEN '2 ' 
  WHEN DAYS(A.FIL_DT) - DAYS(A.FPE) < 120 THEN '4 '
  WHEN DAYS(A.FIL_DT) - DAYS(A.FPE) < 180 THEN '6 '
  WHEN DAYS(A.FIL_DT) - DAYS(A.FPE) > 180 THEN '6+'
 END AS "NBR MTH"                                  
WHERE A.FPE BETWEEN '2006-01-01' AND '2008-12-31'

我需要你的帮助
非常感谢

解决方法

然后写
SELECT YEAR(A.FPE) AS "YEAR",Sum(CASE WHEN DAYS(A.FIL_DT) - DAYS(A.FPE) < 60 
                  THEN 1 Else 0 End) SixtydayCount,Sum(CASE WHEN DAYS(A.FIL_DT) - DAYS(A.FPE) < 120 
                  THEN 1 Else 0 End) OneTwentyDayCount,Sum(CASE WHEN DAYS(A.FIL_DT) - DAYS(A.FPE) < 180 
                  THEN 1  Else 0 End) OneEightyDayCount,Sum(CASE WHEN DAYS(A.FIL_DT) - DAYS(A.FPE) > 180 
                  THEN 1 Else 0 End)  OverOneEightyCount  
    From Table A
    WHERE A.FPE BETWEEN '2006-01-01' AND '2008-12-31'
    Group By YEAR(A.FPE)

如果您希望120天计数和180天计数仅包括60岁以上且不足120岁的人,那么,

SELECT YEAR(A.FPE) AS "YEAR",Sum(CASE WHEN DAYS(A.FIL_DT) - DAYS(A.FPE) Between 60 And 119 
                  THEN 1 Else 0 End) OneTwentyDayCount,Sum(CASE WHEN DAYS(A.FIL_DT) - DAYS(A.FPE) Between 120 And 179 
                  THEN 1  Else 0 End) OneEightyDayCount,Sum(CASE WHEN DAYS(A.FIL_DT) - DAYS(A.FPE) >= 180 
                  THEN 1 Else 0 End)  OverOneEightyCount  
    From Table A
    WHERE A.FPE BETWEEN '2006-01-01' AND '2008-12-31'
    Group By YEAR(A.FPE)
原文链接:/mssql/79892.html

猜你在找的MsSQL相关文章