SQL小计,分组问题

时间:2013-06-26 13:46:03

标签: sql-server-2008 tsql

我很欣赏SQL小计的一些方向。我使用的是SQL Server 2008 R2。

使用的表:

OrderInvoiceHeader.ProvinceCode
OrderInvoiceHeader.InvoiceNumber
OrderInvoiceHeader.BillToCustomer
OrderInvoiceHeader.InvoiceDate
OrderInvoiceHeader.InvoiceAmount
OrderInvoiceHeader.GstAmount
OrderInvoiceHeader.PstAmount

Customer.BillToCustomer
Customer.CustomerName

CanadaProvinces.ProvinceCode
CanadaProvinces.ProvinceName

我必须在查询中显示: 必须显示每个InvoiceNumber,ProvinceName,CustomerName,InvoiceDate,InvoiceAmount,GstAmount和PstAmount。 必须通过ProvinceName包含小计,以包括InvoiceAmount,GstAmount和PstAmount的总和。 必须包含所有省份的小计,以包括InvoiceAmount,GstAmount和PstAmount的总和。

序列必须是省名,客户名,发票编号。

1 个答案:

答案 0 :(得分:0)

就像我说的那样 - 分组:

select 
    InvoiceNumber   = case grouping(InvoiceNumber) when 1 then '<Total>' else InvoiceNumber end, 
    ProvinceName    = case grouping(ProvinceName) when 1 then '<Total>' else ProvinceName end, 
    CustomerName    = case grouping(CustomerName) when 1 then '<Total>' else CustomerName end, 
    InvoiceDate = case grouping(InvoiceDate) when 1 then '<Total>' else InvoiceDate, end  
    sum(InvoiceAmount), sum(GstAmount), sum(PstAmount)
from [table]
group by 
    grouping sets (
        (ProvinceName, InvoiceNumber, CustomerName, InvoiceDate),
        (ProvinceName),
        ()  -- grand total
    )

您可以使用rollupcube来实现此目的,但您必须使用分组([列])来过滤掉不需要的聚合。