我有一个存储过程...它有一个参数:@subCustName
。
此存储过程有一个带group by custName, subCustName
例如:
SELECT custName, subCustName,sum(membership)
FROM CUSTOMER_TABLE
GROUP BY
custName, subCustName
如果参数@subCustName
为'ALL'
,我不想按subCustName分组。
我该怎么做?
提前致谢!
答案 0 :(得分:5)
CASE声明中的小组?
SELECT
CASE WHEN @custName = 'all' THEN '' ELSE custName END AS custName,
subCustName, sum(membership)
FROM
CUSTOMER_TABLE
GROUP BY
CASE WHEN @custName = 'all' THEN '' ELSE custName END, subCustName
我在这里回答的另一个例子:SQL Server 2005/2008 Group By statement with parameters without using dynamic SQL?
答案 1 :(得分:1)
像这样的东西
IF (@subCustName = 'ALL')
SELECT custName, subCustName, 1
FROM CUSTOMER_TABLE
ELSE
SELECT custName, subCustName, sum(membership)
FROM CUSTOMER_TABLE
GROUP BY custName, subCustName
或者您可以动态构建查询