
[英]Display the value of equivalent columns by grouping a column that matches the condition
[英]Group by a column and display the value of the column that matches the condition
我必须按列分组,如果有一个以上的条目,则需要显示一个满足条件的列。 如果只有一个条目,则也应显示。
ID | Name | GroupId
1 | A | x
2 | A | y
3 | B | x
4 | C | z
5 | A | z
6 | B | y
Condition: COUNT(GroupId) > 1 then display y
预期结果:
Name | GroupId
A | y
B | y
C | z
我已经找到内部查询的答案。 不用内部查询就可以做到吗?
注意:如果一个名称有两个或两个以上记录,而没有一个“ y”,则即使没有,也必须显示“ x”
有了这个:
select
name,
case
when count(distinct groupid) = 1 then max(groupid)
when sum(case when groupid = 'y' then 1 end) > 0 then 'y'
else 'x'
end groupid
from tablename
group by name
对于:
CREATE TABLE tablename (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
groupid TEXT
);
INSERT INTO tablename (id,name,groupid) VALUES
(1,'A','x'),
(2,'A','y'),
(3,'B','x'),
(4,'C','z'),
(5,'A','z'),
(6,'B','y'),
(7,'D','k'),
(8,'D','m');
结果是:
| name | groupid |
| ---- | ------- |
| A | y |
| B | y |
| C | z |
| D | x |
参见演示 。
您可以在下面尝试-
select name, case when count(groupid)>2 then 'y' else min(groupid) end as groupid
from tablename a
group by name
您描述:
select t.name,
(case when count(*) > 2 then 'y'
else max(groupid)
end)
from t;
但我认为您确实想要:
select t.name,
(case when min(groupid) <> max(groupid) then 'y'
else max(groupid)
end)
from t;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.