CREATE TABLE [dbo].[A](
[SalesOrg] [nvarchar](4) COLLATE SQL_Latin1_General_CP850_BIN2 NOT NULL,
[SalesGroup] [nvarchar](20) COLLATE SQL_Latin1_General_CP850_BIN2 NOT NULL,
[DocumentType] [nvarchar](25) COLLATE SQL_Latin1_General_CP850_BIN2 NULL,
[DocumentName] [nvarchar](20) COLLATE SQL_Latin1_General_CP850_BIN2 NULL,
[CSName] [nvarchar](50) COLLATE SQL_Latin1_General_CP850_BIN2 NOT NULL,
[Qty] [int] NULL,
[Amount] [numeric](38, 2) NULL
) ON [PRIMARY]
[SalesOrg] [nvarchar](4) COLLATE SQL_Latin1_General_CP850_BIN2 NOT NULL,
[SalesGroup] [nvarchar](20) COLLATE SQL_Latin1_General_CP850_BIN2 NOT NULL,
[DocumentType] [nvarchar](25) COLLATE SQL_Latin1_General_CP850_BIN2 NULL,
[DocumentName] [nvarchar](20) COLLATE SQL_Latin1_General_CP850_BIN2 NULL,
[CSName] [nvarchar](50) COLLATE SQL_Latin1_General_CP850_BIN2 NOT NULL,
[Qty] [int] NULL,
[Amount] [numeric](38, 2) NULL
) ON [PRIMARY]
select case grouping(DocumentType)
when 1 then 'Total'
when 0 then
case grouping(SalesOrg)
when 1 then DocumentType + ' SubTotal'
when 0 then DocumentType
end
end DocumentType,
SalesOrg,SalesGroup,DocumentName,CSName,sum(Qty) qty,sum(Amount) Amt
from [A]
group by DocumentType, SalesOrg,SalesGroup,DocumentName,CSName with rollup
having grouping(SalesOrg) + grouping(SalesGroup) + grouping(DocumentType)
+grouping(DocumentName)+grouping(CSName) = 0
or grouping (SalesOrg) + grouping(SalesGroup)+grouping(DocumentName)+grouping(CSName) = 4
数据如下:
AA S1 G1 A Helen 3 100
AA S2 G1 A Lui 2 200
AA SubTotal NULL NULL NULL NULL 5 300
BB S1 G1 A Helen 3 100
BB S2 G1 A Lui 2 100
BB SubTotal NULL NULL NULL NULL 5 200
Total NULL NULL NULL NULL 10 500