简体   繁体   中英

group by a calculated field in SQL

I have written a query like this

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

I want group by on product? How to do that?

What you need to do is use a subquery for your aliased CASE column. With your query as a subquery, you are able to group by your aliased column.

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

You will need to have the CASE in your Group By as well. You cannot use the alias in 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM