简体   繁体   中英

SQL Server - Mapping table to identify fields to sum

I have a large database of fields around 400, that need to be summed in various different ways.

Currently I do this in Excel with a look up table to identify which field to sum and then use a sum if formula to then sum those columns. How would I replicate this in SQL?

I've seen some examples where you manually type out each field to calculate but this seems very impractical if you are summing up to 300 fields and if there are any changes to that mapping table, then we would have to redo that.

So far my only solution is to copy and paste all the fields to be calculated in excel, and add the correct summation syntax and paste back in to SQL.

Thanks

Lots of ways of doing this;

  1. create a case statement which acts like your sumif and pass the conditions in the case eg CASE WHEN amount >=100 THEN SUM(Amount) END as 'New Column'

  2. Create a function and store all your logic in the function similar to above but easy to maintain should your logic change.

if you post your sumif's with a sample I can help you.

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