我具有以下表格结构,
ID TypeID No
1 10 50
2 20 100
我需要通过检查No
列值来获取TypeID
列值,我做了如下操作,
select case when ( TypeID = 10) THEN NO END AS NO1,
CASE when (TypeID = 20 ) THEN NO END AS NO2 from SAMPLE_TABLE
但是它返回NULL
预期输出为
NO1 NO2
1 0
答案 0 :(得分:2)
您可以使用条件聚合:
with sample_table(ID,TypeID,No) as
(
select 1, 10, 50 union all
select 2, 20, 100
)
select max(case when TypeID = 10 THEN NO END) AS NO1,
max(case when TypeID = 20 THEN NO END) AS NO2
from sample_table;
NO1 NO2
--- ---
50 100
编辑(取决于您的评论)::如果No
列属于bit
类型,请考虑:
select max(case when TypeID = 10 THEN NO+0 END) AS NO1,
max(case when TypeID = 20 THEN NO+0 END) AS NO2
from sample_table;
NO1 NO2
--- ---
1 0
答案 1 :(得分:0)
在这里灵活的一般方法是使用ROW_NUMBER
:
WITH cte AS (
SELECT *, ROW_NUMBER() OVER (ORDER BY TypeID) rn
FROM yourTable
)
SELECT
MAX(CASE WHEN rn = 1 THEN No END) AS NO1,
MAX(CASE WHEN rn = 2 THEN No END) AS NO2
FROM cte;