简体   繁体   中英

sum range of columns SQL

I'm using SQL Server 2016. Suppose I have columns sales1, sales2,..,sales100 in a dataset, along with some other column, say name. I want to write a SQL query like

SELECT name, SUM(sales1), SUM(sales2),..., SUM(sales100)
FROM dataset
GROUP BY name

but I don't believe this is valid SQL syntax.. Is there a shorthand to do this?

There is no shorthand, but SSMS provides a simple way to do this.

From Object Explorer expand your table and drag the column folder to a query window. 
It will give you a csv list of columns.

Oh, but that is not what you wanted!

Replace ',' with '), SUM(' and with minor tweaking you can have the desired string. 

Or you could try this:

DECLARE @SQL VARCHAR(MAX) = ''
SELECT @SQL += 'SUM(' + column_name + '), ' 
FROM information_Schema.COLUMNS 
WHERE table_name = 'mytable' 
AND column_name LIKE 'sales%'
ORDER BY ORDINAL_POSITION
SELECT @SQL

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