按SQL中的计算字段分组

时间:2011-11-28 04:23:02

标签: sql sql-server

我写了一个像这样的查询

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

我想在产品上分组吗? 怎么做?

2 个答案:

答案 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