我写了一个像这样的查询
CASE
WHEN [col1] = 's' THEN '1'
WHEN [col1] = 't' THEN '2'
WHEN [col1] = 'u' THEN '3'
WHEN [col2] = 'v' THEN '4'
.......
END AS product,
SUM(col3)
FROM dbo.TableA
我想在产品上分组吗? 怎么做?
答案 0 :(得分:10)
您需要做的是为别名CASE
列使用子查询。将查询作为子查询,您可以group by
使用别名列。
select product
from
(
select
CASE
WHEN [col1] = 's' THEN '1'
WHEN [col1] = 't' THEN '2'
WHEN [col1] = 'u' THEN '3'
WHEN [col2] = 'v' THEN '4'
END AS product,
SUM(col3) as Col3Sum
FROM dbo.TableA
) a
group by product
答案 1 :(得分:6)
您的CASE
也需要Group By
。你不能在a中使用别名
GROUP BY
SELECT yourColumn, otherColumn
, CASE
WHEN [col1] = 's' THEN '1'
WHEN [col1] = 't' THEN '2'
WHEN [col1] = 'u' THEN '3'
WHEN [col2] = 'v' THEN '4'
END AS Product
, anotherColumn
FROM yourTable
GROUP BY CASE
WHEN [col1] = 's' THEN '1'
WHEN [col1] = 't' THEN '2'
WHEN [col1] = 'u' THEN '3'
WHEN [col2] = 'v' THEN '4'
END