0

我将不胜感激有关 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。必须按省名进行小计,以包括 InvoiceAmount、GstAmount 和 PstAmount 的总和。必须有所有省份的小计以包括 InvoiceAmount、GstAmount 和 PstAmount 的总和。

顺序必须是 ProvinceName、CustomerName、InvoiceNumber。

4

1 回答 1

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
    )

rollup您可以使用or实现此目的cube,但您必须使用 grouping([column]) 过滤掉不需要的聚合。

于 2013-06-26T15:01:00.470 回答