Insert line into a query result (sum)

后端 未结 3 2155
不思量自难忘°
不思量自难忘° 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:33

    Since you are on SQL Server 2005 you need to use rollup like this.

    -- cte for test data
    ;with companyMaster(company, product, price) as
    (select 'CompanyA',    'Product 7',    14.99 union all  
     select 'CompanyA',    'Product 3',    45.95 union all
     select 'CompanyA',    'Product 4',    12.00 union all
     select 'CompanyB',    'Product 3',    45.95 union all
     select 'CompanyC',    'Product 7',    14.99 union all
     select 'CompanyC',    'Product 3',    45.95
    )
    
    select
      company,
      case when grouping(product) = 0
        then product
        else 'Total:'
      end,
      sum(price)
    from companyMaster
    group by company, product with rollup
    having grouping(company) = 0
    

提交回复
热议问题