SQL Server 2008如何分组

时间:2017-04-29 08:17:19

标签: sql-server sql-server-2008 subtotal

我正在尝试在查询中为下表添加小计:

Table A:          Table B:                     Table C:

ID    Name        ID     Name      SubOf       ID      Name      SubOf
===   ======      =====  =======   =====       ======  ======    =====
1     Name 1      1.1    SName 1   1           1.1.1   SSName 1  1.1
2     Name 2      1.2    SName 2   2           1.1.2   SSName 2  1.1
3     Name 3      1.3    SName 3   3           1.1.3   SSName 3  1.1

交易

ID        Qty
======    =======
1.1.1     100
1.1.2     50
1.1.3     200
1.1.1     100
1.1.2     50
1.1.3     200
1.1.1     100
1.1.2     50
1.1.3     200
1.1.1     100
1.1.2     50
1.1.3     200
1.1.1     100

我想选择这样的数据:

期望的结果:

ID        Name        Total
======    =======     =======
1         Name 1      1500    ->Total ID 1 
1.1       sName 1     1500    ->Total ID 1.1
1.1.1     ssName 1     500
1.1.2     ssName 2     200
1.1.3     ssName 3     800

如何添加像结果表一样的小计?提前谢谢。

1 个答案:

答案 0 :(得分:1)

使用GROUP BY对数量进行求和,UNION ALL将smae结果中的不同分组和基本查询的finnaly CTE结合起来

; with cte as
(
    select  ID1 = a.ID, Name1 = a.Name,
            ID2 = b.ID, Name2 = b.Name,
            ID3 = c.ID, Name3 = c.Name,
            t.Qty
    from    Trans t
            inner join tableC c on  t.ID    = c.ID
            inner join tableB b on  c.SubOf = b.ID
            inner join tableA a on  b.SubOf = a.ID
)
select  ID = ID1, Name = Name1, sum(Qty)
from    cte
group by ID1, Name1
union all
select  ID = ID2, Name = Name2, sum(Qty)
from    cte
group by ID2, Name2
union all
select  ID = ID3, Name = Name3, sum(Qty)
from    cte
group by ID3, Name3