2014-09-05 48 views
0

我有一個在SQL Server中的表格,下面的條目。如何分組透視列?

Name Type  Amount 
------------------------------ 
ABC  Opening  100 
CBD  Invoice  200 
ABC  Spreadsheet 250 
FBD  Closing  400 

我想創建一個基於上述的數據透視表,但是,我也試圖將類型列分成3個不同的列。

  • 開放
  • 下面關閉
  • 活性(其他)

見表。這可能嗎?

Name Opening Activity Closing 
---------------------------------------- 
ABC  100   200   0 
CBD  0   250   0 
FBD  0   0  400 

代碼到目前爲止

select * 
from 
    (
     select [Name] 
       ,[Type] 
       ,[Amount] 
     from my_Table 
    ) a 
    pivot(sum(Amount) 
    for Type in (Opening], [Closing]) 
    )as pvt 

我如何去這樣做呢?

回答

3

我建議用聚合函數CASE表達式這樣做:

select 
    name, 
    sum(case when type = 'Opening' then Amount else 0 end) Opening, 
    sum(case when type not in ('Opening', 'Closing') then Amount else 0 end) Activity, 
    sum(case when type = 'Closing' then Amount else 0 end) Closing 
from my_table 
group by name; 

SQL Fiddle with Demo。您將使用CASE邏輯專門查找OpeningClosing值,然後最後一列將對Type不是OpeningClosing的行進行求和。

您可以使用PIVOT獲得結果,您只需要在應用pivot函數之前關聯「其他」活動。爲此,您可以使用子查詢:

select name, Opening, Activity, Closing 
from 
(
    select 
    name, 
    type = case 
       when type not in ('Opening', 'Closing') 
       then 'Activity' 
       else type 
      end, 
    amount 
    from my_table 
) d 
pivot 
(
    sum(amount) 
    for type in (Opening, Activity, Closing) 
)piv; 

SQL Fiddle with Demo