Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Group by a result of Case Substring SQL Query

I am having this query below and am unable to get the result of the full quantity when I use group by

SELECT CASE SUBSTRING(Data_Code, 3,1) 
         WHEN '1' THEN 'SS' 
         ELSE 'FW' 
       END + SUBSTRING(Data_Code, 1,2) [MyNewColumn]
SUM(QUANTITY) 
FROM [MyTable]
GROUP BY Data_Code

below is the sample of the table

|DataCode|Quantity|
|22263738| 10     |
|22251616| 15     |

am expecting to have a result of 25

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Looking forwards to your kind help

Thanks

>Solution :

Just use a sub-query

SELECT
    MyNewColumn
    , SUM(QUANTITY) 
FROM (
    SELECT
        QUANTITY
        , CASE SUBSTRING(Data_Code, 3,1) 
        WHEN '1' THEN 'SS' 
        ELSE 'FW'
        END + SUBSTRING(Data_Code, 1,2) MyNewColumn
    FROM MyTable
) X
GROUP BY MyNewColumn;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading