我有一个带有ID和D_DESC列的映射表。我想传递一个D_DESC值,传递多个ID,例如:
ID D_DESC
1 DESC_ID1
2 DESC_ID2
3 DESC_ID3
结果应为
D_DESC1 D_DESC2
DESC_ID1 DESC_ID2
我做了这个查询:
SELECT t1.D_DESC AS DESC_1,t2.D_DESC AS DESC_2
FROM Tabel t1,Tabel t2
WHERE '1'=t1.ID
AND '2'=t2.ID
返回正是我想要的,但如果我想在id未通过的情况下也将null值放入。例如,我还想从查询中显示此结果(
SELECT t1.D_DESC AS DESC_1,t2.D_DESC AS DESC_2 FROM Tabel t1,Tabel t2 WHERE '1'=t1.ID AND ''=t2.ID;
):
D_DESC1 D_DESC2
DESC_ID1 null
推荐?
答案 0 :(得分:3)
如果您希望只有一行具有不同的IDS
,那么您可以这样做:
select max(case when id = 1 then D_DESC end) DESC_1,
max(case when id = 2 then D_DESC end) DESC_2
from table t;
答案 1 :(得分:0)
这是PIVOT
操作。
SELECT *
FROM Table1
PIVOT(MAX(D_DESC) FOR id IN (
1 AS D_DESC1
,2 AS D_DESC2
,3 AS D_DESC3
));
这给出了:
| D_DESC1 | D_DESC2 | D_DESC3 |
|----------|----------|----------|
| DESC_ID1 | DESC_ID2 | DESC_ID3 |
如果您想为NULL
传递id2
,请写
SELECT *
FROM Table1
PIVOT(MAX(D_DESC) FOR id IN (
1 AS D_DESC1
,NULL AS D_DESC2
,3 AS D_DESC3
));
给出了
| D_DESC1 | D_DESC2 | D_DESC3 |
|----------|---------|----------|
| DESC_ID1 | (null) | DESC_ID3 |