Insert line into a query result (sum)

后端 未结 3 1971
不思量自难忘°
不思量自难忘° 2021-01-05 20:59

I have a report that shows products that customers have ordered, along with their prices:

CompanyA    Product 7    14.99  
CompanyA    Product 3    45.95
Com         


        
3条回答
  •  囚心锁ツ
    2021-01-05 21:31

    Thanks for everyone's feedback/help, it at least got me thinking of different approaches. I came up with something that doesn't depend on what version of SQL Server I'm using (our vendor changes versions often so I have to be as cross-compliant as possible).

    This might be considered a hack (ok, it is a hack) but it works, and it gets the job done:

    SELECT company
       , product
       , price
    FROM companyMaster
    ORDER BY company,
       , product,
       , price
    
    UNION
    
    SELECT company + 'Total'
       , ''
       , SUM(price)
    FROM companyMaster
    GROUP BY company
    
    ORDER BY company;
    

    This solution basically uses the UNION of two select statements. The first is exactly like the orginal, the second produces the sum line I needed. In order to correctly locate the sum line, I did a string concatenation on the company name (appending the word 'Total'), so that when I sort alphabetically on company name, the Total row will show up at the bottom of each company section.

    Here's what the final report looks like (not exactly what I wanted but functionally equivalent, just not very pretty to look at:

    CompanyA    Product 7    14.99  
    CompanyA    Product 3    45.95
    CompanyA    Product 4    12.00
    CompanyA Total           72.94
    CompanyB    Product 3    45.95
    CompanyB Total           45.95
    CompanyC    Product 7    14.99
    CompanyC    Product 3    45.95
    CompanyC Total           60.94
    

提交回复
热议问题