选择并选择Count(在同一查询中聚合和非聚合)

时间:2014-02-12 10:59:20

标签: sql-server

我有下面的脚本。输出是行/列格式的XML数据。还带有变量[Name]。

此时我只使用select语句。我需要的是select语句中的一些列(不是全部)的总和

需要总计的列是:ColumnA,ColumnB,ColumnC

剧本:

;With CTE
AS
(
SELECT [Month]
,[Name]
,[Month_Code]
,[ColumnA]
,[ColumnB]
,[ColumnC]
FROM Fact_A
INNER JOIN Dim_A on Fact_A.Key = Dim_A.Key
INNER JOIN Dim_B on Fact_A_Key = Dim_B.Key
WHERE Fiscal_Year = '20132014'
)

select [Name] AS [@name],
(select [Month] as [column],
null as tmp,
ColumnA as [column],
null as tmp,
ColumnB as [column],
null as tmp,
ColumnC as [column]
from CTE
where [Name] = t.[Name]
Order BY [Month_Code]

for xml path('row'),type) as [*]
from (select distinct [Name] from CTE)t
for xml path('variable'),root('data')

1 个答案:

答案 0 :(得分:0)

如果我理解正确并且您想要每个群集和月份的这些列的总计,那么您可以尝试:

SELECT Month
,Name
,Month_Code
,SUM(ColumnA) AS A
,SUM(ColumnB) AS B
,SUM(ColumnC) AS C
FROM Fact_A
INNER JOIN Dim_A on Fact_A.Key = Dim_A.Key
INNER JOIN Dim_B on Fact_A_Key = Dim_B.Key
GROUP BY Month, Name, Month_Code
WHERE Fiscal_Year = '20132014'

如果您不想对所有列求和,则可以使用另一个聚合而不是SUM(),例如任何列的COUNT()或MAX()