我需要显示每个 'id' 有多少不同的值。
应该是这样的:
id | component_a | component_b | component_c
--------------------------------------------------
KLS11 | none | one | none
KLS12 | one | one | none
KLS13 | several | one | none
KLS14 | one | one | one
KLS15 | one | several | several
我有下表(table_a):
id | component_a | component_b | component_c
--------------------------------------------------
KLS11 | | a |
KLS12 | a | a |
KLS13 | a | a |
KLS13 | b | a |
KLS14 | a | a | a
KLS15 | a | a | a
KLS15 | a | b | b
这里是一个例子/解释:
- KLS13 在 component_a ( a,b ) 中有不同的值 - 所以它应该显示 'several'
- KLS13 在 component_b ( a,a ) 中具有相同的值 - 所以它应该显示 '一个'
- KLS13 在 component_c 中没有值 - 所以它应该显示 'none'
这是我的 SQL 代码:
我已经为 component_a 做过,但它不起作用。我做错了什么?
SELECT
CASE WHEN component_a is NULL THEN 'none'
WHEN (SELECT count(DISTINCT component_a)
FROM table_a
WHERE id=(SELECT id
FROM table_a GROUP BY id HAVING count(*)>1)>1 THEN 'several'
WHEN (SELECT count(DISTINCT component_a)
FROM table_a
WHERE id=(SELECT id
FROM table_a GROUP BY id HAVING count(*)>1)=1 THEN 'one'
END as componentA
FROM table_a
我是 SQL 的初学者,所以我将不胜感激。
祝你有美好的一天
最佳答案
您收到 ORA-00936 错误(我认为)是因为您没有关闭每个 when
分支中的括号;添加额外的关闭会将错误更改为“ORA-01427:单行子查询返回多行”,因为子子选择(带有 having
子句)返回多行 - 没有相关性。
您不需要子查询,只需将不同的值计算为 case
构造的一部分,即可创建 searched case expression :
select id,
case count(distinct component_a)
when 0 then 'none'
when 1 then 'one'
else 'several'
end as component_a
from table_a
group by id
order by id;
ID COMPONENT_A
----- -----------
KLS11 none
KLS12 one
KLS13 several
KLS14 one
KLS15 one
然后重复其他列:
select id,
case count(distinct component_a)
when 0 then 'none'
when 1 then 'one'
else 'several'
end as component_a,
case count(distinct component_b)
when 0 then 'none'
when 1 then 'one'
else 'several'
end as component_b,
case count(distinct component_c)
when 0 then 'none'
when 1 then 'one'
else 'several'
end as component_c
from table_a
group by id
order by id;
ID COMPONENT_A COMPONENT_B COMPONENT_C
----- ----------- ----------- -----------
KLS11 none one none
KLS12 one one none
KLS13 several one none
KLS14 one one one
KLS15 one several several
关于SQL - CASE WHEN 计算不同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23078647/