PIVOT一个水平表与总计

时间:2014-07-24 14:34:59

标签: sql sql-server sql-server-2008 stored-procedures

我有一个表格,其中包含每月销售总额的数据,每列按月拆分。

E.g。

InvJan | InvFeb | InvMar ... TotalInv | CrdJan | CrdFeb | CrdMar  ...TotalCrd
------------------------------------------------------------------------------
 100   |   120  |   200  ...   420    |   0    |   140  |   30    ... 170

您可以看到阅读的所有列。 我希望能够PIVOT然后看起来像这样:

     |     INV            CRD 
------------------------------
JAN  |     100             0          
FEB  |     120            140
MAR  |     200             30 
 .   |      .              .
 .   |      .              .
 .   |
______________________________
TOTAL|     420            170

我可以使用Pivots吗?我对它们的经验不太好......或者有更好的方法吗?

3 个答案:

答案 0 :(得分:1)

使用2 unpivot s。

select replace(inv,'inv',''), invval, crdval
from
(select * from yourtable unpivot (invval for inv in (invjan,invfeb,invmar,totalinv)) u) u1
unpivot (crdval for crd in (crdjan,crdfeb,crdmar, totalcrd)) u2
where replace(inv,'inv','')=replace(crd,'crd','')

或者您可以使用union

select 'jan', invjan as inv, crdjan as crd from yourtable
union all select 'feb', invfeb, crdfeb from yourtable
union all select 'mar', invmar, crdmar from yourtable
...

答案 1 :(得分:1)

首先定义什么是Inv和Crd:

SELECT 'Inv' as Types, InvJan AS Jan, InvFeb as Feb, InvMar as Mar
INTO #testTable
FROM @table
UNION
SELECT 'Crd' as Types, CrdJan AS Jan, CrdFeb as Feb, CrdMar as Mar
FROM @table

然后Unpivot this |

select months, Types, data
INTO #test2
from #testTable
unpivot
(
  data
  for months in (jan, Feb, Mar)
) u;

然后按照你的意愿放置

select * 
from #test2
pivot (SUM (data) for Types in (Inv, Crd)) as T

答案 2 :(得分:1)

这种类型的数据转换列到行中称为UNPIVOT。由于您使用的是SQL Server 2008,因此您应该可以使用CROSS APPLY成对地取消对列的删除:

select Mnth, Inv, Crd
from yourtable
cross apply
(
    values
        ('Jan', InvJan, CrdJan),
        ('Feb', InvFeb, CrdFeb),
        ('Mar', InvMar, CrdMar),
        ('Apr', InvApr, CrdApr),
        ('May', InvMay, CrdMay)
        -- insert more columns here
) c (Mnth, Inv, Crd);