簡體   English   中英

SQL數據透視表不起作用

[英]SQL Pivot Table isn't working

SQL 2005

我有一個臨時表:

 Year         PercentMale   PercentFemale  PercentHmlss   PercentEmployed  TotalSrvd
 2008           100                0           0              100              1
 2009           55                40           0               80             20
 2010           64                35           0               67            162
 2011           69                27           0               34            285
 2012           56                43          10                1             58

我想創建一個查詢以顯示如下數據:

                    2008    2009    2010    2011    2012
 PercentMale         100     55      64      69      56 
 PercentFemale        -      40      35      27      43 
 PercentHmlss         -      -       -       -       10 
 PercentEmployed     100     80      67      34      1 
 TotalSrvd            1      20     162     285      58 

我可以使用數據透視表來完成此操作嗎? 如果是這樣,怎么辦? 我嘗試使用樞軸,但沒有成功。

 select PercentHmlss,PercentMale,Percentfemale,
     PercentEmployed,[2008],[2009],[2010],[2011],[2012] from 

 (select PercentHmlss,PercentMale, Percentfemale, PercentEmployed,
     TotalSrvd,year from @TempTable)as T

  pivot (sum (TotalSrvd) for year 
     in ([2008],[2009],[2010],[2011],[2012])) as pvt

結果如下:

 PercentHmlss   PercentMale     Percentfemale PercentEmployed [2008]  [2009]    [2010]      [2011]   [2012]
    0               55              40            80           NULL     20      NULL         NULL     NULL
    0               64              35            67           NULL    NULL     162            NULL  NULL
    0               69              27            34           NULL    NULL     NULL          285     NULL
    0              100               0           100             1     NULL     NULL         NULL    NULL
   10               56              43             1           NULL    NULL     NULL         NULL     58

謝謝。

為此,您需要先執行UNPIVOT ,然后執行PIVOT

SELECT *
from
(
  select year, quantity, type
  from 
  (
    select year, percentmale, percentfemale, percenthmlss, percentemployed, totalsrvd
    from t
  ) x
  UNPIVOT 
  (
    quantity for type
    in 
    ([percentmale]
     , [percentfemale]
     , [percenthmlss]
     , [percentemployed]
     , [totalsrvd])
  ) u
) x1
pivot
(
  sum(quantity)
  for Year in ([2008], [2009], [2010], [2011], [2012])
) p

查看帶有演示SQL Fiddle

編輯進一步的解釋:

您已與嘗試的PIVOT查詢保持緊密聯系,因為您以所需的列格式獲得了Year的數據。 不過,既然你想這是包含在最初的列中的數據percentmalepercentfemale等數據的行-你需要首先unpivot的數據。

基本上,您要做的是獲取原始數據並將其全部基於年份放置在行中。 UNPIVOT將以( Demo )格式放置數據:

Year    Quantity    Type
2008    100         percentmale
2008    0           percentfemale
etc

將數據轉換為這種格式后,即可執行PIVOT以獲取所需的結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM