从参数确定分组 -

时间:2016-09-28 18:44:49

标签: tsql group-by

这是如何有效的:

ALTER PROCEDURE [StoredProcedure] 

@abcID int = null -- optional param

SELECT columnJ, columnK, Count(eID) AS Num, Sum(OutXYZ) as TotalProdXYZ, Sum(RawXYZ) as TotalRawXYZ
FROM [v_ViewTable]
WHERE (@abcID IS NULL OR (abcID = @abcID))

GROUP BY columnJ, columnK

但是这会抛出一个" columnJ在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。"

ALTER PROCEDURE [StoredProcedure] 

@abcID int = null -- optional param

-- if 0: Group by columnJ, columnK
-- else: Group by columnK, columnJ
, @Grouping int = null  

SELECT columnJ, columnK, Count(eID) AS Num, Sum(OutXYZ) as TotalProdXYZ, Sum(RawXYZ) as TotalRawXYZ
FROM [v_ViewTable]
WHERE (@abcID IS NULL OR (abcID = @abcID))

GROUP BY
CASE WHEN @Grouping = 0 THEN columnJ ELSE columnK END
,CASE WHEN @Grouping = 0 THEN columnK ELSE columnJ END

我的CASE声明出了什么问题?基本上,如果@Grouping = 0,我希望group by为J,K,如果有的话,它应该是K,J

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

正如消息所示,columnJcolumnK未包含在聚合函数或第二种情况下的GROUP BY子句中。您应该在GROUP BY部分中的选择列表中使用字段或精确表达式。

所以下面的陈述是可以的:

SELECT CASE WHEN @Grouping = 0 THEN columnJ ELSE columnK END,
       CASE WHEN @Grouping = 0 THEN columnK ELSE columnJ END,
       Count(eID) AS Num, Sum(OutXYZ) as TotalProdXYZ, Sum(RawXYZ) as TotalRawXYZ
FROM [v_ViewTable]
WHERE (@abcID IS NULL OR (abcID = @abcID))

GROUP BY
CASE WHEN @Grouping = 0 THEN columnJ ELSE columnK END
,CASE WHEN @Grouping = 0 THEN columnK ELSE columnJ END