使用别名的SQL Server 2008汇总

时间:2018-10-23 22:44:05

标签: sql sql-server-2008

我有以下查询,我的行总计将显示NULL,因为标题和总和是准确的。我尝试使用带有case语句的分组似乎无济于事。我在该站点上的搜索未提供有效的解决方案。如果使用以下解决方案,则会出现错误:

  

无法绑定多部分标识符

CASE
   WHEN GROUPING(B.Department) = 1  
      THEN 'Total'
      ELSE [B.Department]
END [B.Department],

Select

B.Department,
SUM(CASE datepart(month, [Created on]) WHEN 1 Then 1 ELSE 0 END) AS 'January'
SUM(CASE datepart(month, [Created on]) WHEN 2 Then 1 ELSE 0 END) AS 'February'
SUM(CASE datepart(month, [Created on]) WHEN 3 Then 1 ELSE 0 END) AS 'March'
.
.
SUM(CASE datepart(year, [Created on]) WHEN 2018 Then 1 ELSE 0 END) AS 'YTD'

FROM 
    [Table Cases] A
LEFT JOIN 
    [Table Departments] B ON A.Department = B.Dept
GROUP BY 
    B.Department WITH ROLLUP 

谢谢:-)

1 个答案:

答案 0 :(得分:0)

通常,这可以通过使用COALESECE()ISNULL()来解决,例如

Select
      COALESECE(B.Department,'Total') as Department
    , SUM(CASE datepart(month, [Created on]) WHEN 1 Then 1 ELSE 0 END) AS 'January'
    , SUM(CASE datepart(month, [Created on]) WHEN 2 Then 1 ELSE 0 END) AS 'February'
    , SUM(CASE datepart(month, [Created on]) WHEN 3 Then 1 ELSE 0 END) AS 'March'
    ...
    , SUM(CASE datepart(year, [Created on]) WHEN 2018 Then 1 ELSE 0 END) AS 'YTD'
FROM [Table Cases] A
INNER join [Table Departments] B On A.Department = B.Dept
GROUP BY B.Department WITH ROLLUP 

在按部门汇总时,您真的需要左联接吗?