简体   繁体   中英

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.

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

many thanks

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

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