我有一張桌子:
| ID | col1 | col2 | col3 | col4 | col5 |
|---|---|---|---|---|---|
| 1 | 是 | G | 加州 | 達 | EA |
| 2 | 是 | G | 加州 | 達 | EA |
| 3 | 是 | 問 | 加州 | 達 | EA |
| 1 | X | G | 類風濕關節炎 | 達 | EA |
| 2 | X | G | 加州 | 達 | EA |
| 3 | X | 問 | 加州 | 達 | EA |
對于 col1 和 col2,我想創建 4 個額外的列。兩個用于 col1 (X,Y) 的不同值,兩個用于 col2 (G,Q) 的不同值。例如,如果 ID 1 有 col1 = X,那么我想在 col1_X 下顯示“Y”。我怎么做?我想我需要一個資料透視/分組依據,因為我想消除重復的資料行。
期望的輸出:
| ID | col3 | col4 | col5 | col1_X | col1_Y | col2_G | col2_Q |
|---|---|---|---|---|---|---|---|
| 1 | 加州 | 達 | EA | 是 | 是 | 是 | ? |
| 1 | 類風濕關節炎 | 達 | EA | 是 | 是 | 是 | ? |
| 2 | 加州 | 達 | EA | 是 | 是 | 是 | ? |
| 3 | 加州 | 達 | EA | 是 | 是 | ? | 是 |
uj5u.com熱心網友回復:
CASE對每個新列使用一個運算式:
SELECT DISTINCT ID, col3, col4, col5,
CASE WHEN col1 = 'X' THEN 'Y' ELSE 'N' END col1_X,
CASE WHEN col1 = 'Y' THEN 'Y' ELSE 'N' END col1_Y,
CASE WHEN col2 = 'G' THEN 'Y' ELSE 'N' END col2_G,
CASE WHEN col2 = 'Q' THEN 'Y' ELSE 'N' END col2_Q
FROM tablename;
請參閱演示。
uj5u.com熱心網友回復:
這是一個幼稚的解決方案,但可能有助于以更動態的方式解決問題:
drop table if exists #test;
drop table if exists #result;
create table #test (
[ID] int,
[col1] varchar(1),
[col2] varchar(1),
[col3] varchar(2),
[col4] varchar(2),
[col5] varchar(2));
insert into #test ([ID], [col1], [col2], [col3], [col4], [col5])
values
(1, 'Y', 'G', 'CA', 'DA', 'EA'),
(2, 'Y', 'G', 'CA', 'DA', 'EA'),
(3, 'Y', 'Q', 'CA', 'DA', 'EA'),
(1, 'X', 'G', 'RA', 'DA', 'EA'),
(2, 'X', 'G', 'CA', 'DA', 'EA'),
(3, 'X', 'Q', 'CA', 'DA', 'EA');
-- create the output table
select
distinct ID, col3, col4, col5,
'N' as col1_X, 'N' as col1_Y, 'N' as col2_G, 'N' as col2_Q
into #result
from #Test;
-- update the results
update t1
set t1.col1_X = 'Y'
from #result t1
where exists (select * from #test t2
where t2.ID = t1.ID and t2.col3 = t1.col3 and t2.col4 = t1.col4 and t2.col5 = t1.col5
and t2.col1 = 'X');
update t1
set t1.col1_Y = 'Y'
from #result t1
where exists (select * from #test t2
where t2.ID = t1.ID and t2.col3 = t1.col3 and t2.col4 = t1.col4 and t2.col5 = t1.col5
and t2.col1 = 'Y');
update t1
set t1.col2_G = 'Y'
from #result t1
where exists (select * from #test t2
where t2.ID = t1.ID and t2.col3 = t1.col3 and t2.col4 = t1.col4 and t2.col5 = t1.col5
and t2.col2 = 'G');
update t1
set t1.col2_Q = 'Y'
from #result t1
where exists (select * from #test t2
where t2.ID = t1.ID and t2.col3 = t1.col3 and t2.col4 = t1.col4 and t2.col5 = t1.col5
and t2.col2 = 'Q');
select * from #result;
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/489454.html
上一篇:Sqlserver:連接兩個表并使用子查詢選擇多個列值
下一篇:觸發多行動作
