Case Stament,GroupBy和Count没有正确分组

时间:2017-04-20 18:24:39

标签: count group-by case totals

我有一个SQL,它使用case语句来组合两个字段和一个带有count的groupby。 我的查询没有错误,但它没有对具有两个不同名称但在case语句中给出相同名称的数据进行分组/计数。

SELECT   EMPLY, 
         Case when CCode = 'L1' then 'LongTerm' 
              when CCode = 'D1' then 'ShortTerm' 
              when RPolicy = 'C1' then 'Custom' 
              when RPolicy = 'H1' then 'Custom' end AS [FileType], 
         Count(AccountNumber) AS Total 
FROM     dbo.Accounts 
WHERE    Date like '%2017%' 
GROUP BY EMPLY, RPolicy, CCode
ORDER BY 1

我需要知道的是如何按新栏目“文件类型”进行分组?

输出:

EMPLY   File Type   Total
EMPLY1  LongTerm    12
EMPLY1  Custom      1
EMPLY1  Custom      5
EMPLY1  ShortTerm   3
EMPLY2  LongTerm    16
EMPLY2  Custom      3
EMPLY2  Custom      6
EMPLY2  ShortTerm   8
EMPLY3  LongTerm    20
EMPLY3  Custom      2
EMPLY3  Custom      10
EMPLY3  ShortTerm   4

任何帮助将不胜感激。 我正在使用AQT / SQL Server

1 个答案:

答案 0 :(得分:0)

这是你想要做的吗?

(你不能在组中使用别名,因为它在select之前执行,但是,你可以使用完整的case语句!)

SELECT   EMPLY, 
         Case when CCode = 'L1' then 'LongTerm' 
              when CCode = 'D1' then 'ShortTerm' 
              when RPolicy in ('C1','H1') then 'Custom' end AS [FileType], 
         Count(AccountNumber) AS Total 
FROM     dbo.Accounts 
WHERE    Date like '%2017%' 
GROUP BY EMPLY, Case when CCode = 'L1' then 'LongTerm' 
              when CCode = 'D1' then 'ShortTerm' 
              when RPolicy In ('C1','H1') then 'Custom' end
ORDER BY EMPLY, FileType, Total

这个子查询也应该有用,但它是开销。

SELECT   A.EMPLY
       , A.FileType
       , Count(1) AS Total 
FROM     (SELECT EMPLY
               , Date
               , Case when CCode = 'L1' then 'LongTerm' 
                      when CCode = 'D1' then 'ShortTerm' 
                      when RPolicy in ('C1','H1') then 'Custom' 
                 end AS FileType
         FROM dbo.Accounts) A
WHERE    A.Date like '%2017%' 
GROUP BY A.EMPLY, A.FileType
ORDER BY A.EMPLY, A.FileType