数据库不使用存储过程,如何实现分组合计查询?
有张范例表如下:
怎样才能查出如下图:
注意事项:
图1表数据是范例,实际会有更多。
条件:
不允许使用存储过程
若非必要,不能使用游标
回答
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 ]
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
以上是 数据库不使用存储过程,如何实现分组合计查询? 的全部内容, 来源链接: utcz.com/a/44678.html