2010-07-16 113 views
1

我的基表是這樣的:T-SQL從一個表變化的數據,並插入到另一個表

ColumnA|ColumnB 
--------------- 
    A | C1 
    A | C2 
    A | C3 
    B | C1 
    B | C3 
    C | C4 

我想從基礎表中讀取記錄,並將其寫入到見下表:

ColumnA | C1 | C2 | C3 | C4 
---------------------------- 
    A | Y | Y | Y | N 
    B | Y | N | Y | N 
    C | N | N | N | Y 

我不想使用遊標,但我不知道這是否可能。

感謝

+0

就像一個數據透視表,對嗎? – MJB 2010-07-16 15:17:05

+0

是的,我認爲但我不知道如何在這裏使用 – oshin 2010-07-16 15:18:12

+0

應C-> C4是Y? 你想建立一個真值表還是隻顯示輸出? – 2010-07-16 15:22:49

回答

1

一個(通常快速)的方法是group by

insert NewTable (ColumnA, C1, C2, C3, C4) 
select ColumnA 
,  IsNull(max(case when ColumnB = 'C1' then 'Y' end), 'N') 
,  IsNull(max(case when ColumnB = 'C2' then 'Y' end), 'N') 
,  IsNull(max(case when ColumnB = 'C3' then 'Y' end), 'N') 
,  IsNull(max(case when ColumnB = 'C4' then 'Y' end), 'N') 
from OldTable 
group by 
     ColumnA 

另一種方式是子查詢,如:

insert NewTable (ColumnA, C1, C2, C3, C4) 
select src.ColumnA 
,  case when exists (select * from OldTable ot 
          where ot.ColumnA = src.ColumnA and ot.ColumnB = 'C1') 
        then 'Y' else 'N' end 
,  case when exists (select * from OldTable ot 
          where ot.ColumnA = src.ColumnA and ot.ColumnB = 'C2') 
        then 'Y' else 'N' end 
,  case when exists (select * from OldTable ot 
          where ot.ColumnA = src.ColumnA and ot.ColumnB = 'C3') 
        then 'Y' else 'N' end 
,  case when exists (select * from OldTable ot 
          where ot.ColumnA = src.ColumnA and ot.ColumnB = 'C4') 
        then 'Y' else 'N' end 
from (
     select distinct ColumnA 
     from OldTable 
     ) src 

或者,改編自克里斯潛水員的回答,用pivot

select ColumnA 
,  case when C1 > 0 then 'Y' else 'N' end C1 
,  case when C2 > 0 then 'Y' else 'N' end C2 
,  case when C3 > 0 then 'Y' else 'N' end C3 
,  case when C4 > 0 then 'Y' else 'N' end C4 
from OldTable src 
pivot (
     count(ColumnB) 
     for ColumnB IN ([C1], [C2], [C3], [C4]) 
     ) pvt 
+0

+1。如果在設計時知道樞軸的列數,並且足夠小以便通過複製/粘貼這些子查詢來管理,則這更容易。 – 2010-07-16 15:23:40

+0

在爲什麼你在使用MAX? – oshin 2010-07-16 15:29:52

+0

@oshin:您必須爲數據庫指定一個聚合多行數值的方法。 max()中的表達式返回'Y'表示匹配,'null'表示不匹配。如果找到匹配的行,那麼'max()'是'Y',否則是'null'。 – Andomar 2010-07-16 15:32:39

0

假設你可以選擇你喜歡的信息,那麼你可以編寫插件作爲選擇的結果。

+0

你是否在我的朋友那裏讀過這個問題? – oshin 2010-07-16 15:16:01

2

看看PIVOT命令。從那裏,你可以做一個INSERT INTO ... SELECT ...

SELECT ColumnA, [C1], [C2], [C3], [C4] 
FROM (SELECT * FROM table) t 
PIVOT 
(
Count(ColumnB) 
FOR ColumnB IN ([C1], [C2], [C3], [C4]) 
) As Pvt 
+0

因爲我只需要Y或N,我如何在這裏使用case語句? 我試圖計數(columnB)= 0,然後'N'ELSE'Y'END但我得到錯誤: 關鍵字'case'附近的語法不正確。 – oshin 2010-07-16 15:47:53

+0

@oshin:在要求苛刻的<聚合函數>(<列聚合>)時,樞軸是不靈活的。在我的答案中加入了一個數據透視表,但如果您願意,請接受Chris Diver的答案:) – Andomar 2010-07-16 15:52:15

+0

您必須在select語句中的每個'[Cx]'處添加一個案例。 – 2010-07-16 15:58:23

相關問題