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

How to add a column to an existing SQL output?

I am new to Transact-SQL, assume I have a sql table

SELECT 
    Foods,
    Count(*) as total_count
FROM [SuperMarket].[dbo].[Grocery]
GROUP BY Foods
ORDER BY Foods DESC

output:

Foods total_count
3 27
2 35
1 109
0 783

Is it possible to add an extra column in the existing sql output such as following. However, there is NO ‘Name’ in the original sql db.

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

Foods Name total_count
3 meat 27
2 fish 35
1 fruit 109
0 pasta 783

many thanks

>Solution :

You can use a case statement:

SELECT 
    Foods,
    CASE
    WHEN FOODS = 3 THEN 'meat'
    WHEN FOODS = 2 THEN 'fish'
    WHEN FOODS = 1 THEN 'fruit'
    WHEN FOODS = 0 THEN 'pasta'
    END as Name,
    Count(*) as total_count
FROM [SuperMarket].[dbo].[Grocery]
GROUP BY Foods
ORDER BY Foods DESC
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