ms sql中的数据透视查询中的水平和垂直总计

时间:2013-05-30 13:13:17

标签: sql tsql sql-server-ce pivot

我正在尝试做纵向和横向的总列,请参阅以下查询, 我能够做垂直总计。

Select
  U_POD 'City',
  Sum([Customer TS Pending])  as    CTST ,
  sum([Pending])as P,
  sum([Pending SQ])as 'PSQ',
  sum([Tracking])as Tracking,
  SUM([Open])as Openn
from 
(
  Select T1.U_POD,T2.Name 
  from OSCL T0 
  inner join OCRD T1 
    on T0.Customer=T1.cardcode 
  inner join OSCS T2 
    on T2.statusID=T0.Status
)Service
Pivot
(
  count(Name)
  for Name IN ([Pending],[Pending SQ],[Tracking],[Open],[Customer TS Pending])
)pvt
group by rollup (pvt.U_POD)

1 个答案:

答案 0 :(得分:1)

group by rollup将为您提供总计的最后一行,但如果您要查找包含总计的列,则可以在查询中添加新的计算列:

 sum([Customer TS Pending] + [Pending] + [Pending SQ] + [Tracking] + [Open]) Total

这将产生完整的查询:

Select
  U_POD 'City',
  Sum([Customer TS Pending])  as    CTST ,
  sum([Pending])as P,
  sum([Pending SQ])as 'PSQ',
  sum([Tracking])as Tracking,
  SUM([Open])as Openn,
  sum([Customer TS Pending] + [Pending] + [Pending SQ] + [Tracking] + [Open]) Total
from 
(
  Select T1.U_POD,T2.Name 
  from OSCL T0 
  inner join OCRD T1 
    on T0.Customer=T1.cardcode 
  inner join OSCS T2 
    on T2.statusID=T0.Status
)Service
Pivot
(
  count(Name)
  for Name IN ([Pending],[Pending SQ],[Tracking],[Open],[Customer TS Pending])
)pvt
group by rollup (pvt.U_POD)