[英]SQL Group By, case when on aggregated
Can't wrap my mind around the next task: I have a table, with some key
, which represents some kind of group id.无法围绕下一个任务进行思考:我有一张桌子,上面有一些
key
,它代表某种组 ID。 I would like to GROUP BY
by this key and in resulted table show some columns from this table depending on the column value: If all the values in this group by this key
in col1
are equal (same number or text), then show this exact value, if they are different (at least one of them) - show some kind like "Others".我想按此键进行
GROUP BY
并在结果表中根据列值显示该表中的一些列:如果col1
中此key
该组中的所有值都相等(相同的数字或文本),则显示此精确值,如果它们不同(至少其中一个) - 显示某种类似“其他”的东西。
Example例子
key col1
1 1
1 1
1 1
2 4
2 5
Resulted table:结果表:
key col1
1 1
2 Others
Postgres 9.4, if this matters. Postgres 9.4,如果这很重要。
You can use aggregation and case
:您可以使用聚合和
case
:
select key,
(case when min(col1) = max(col1) then min(col1)
else 'others'
end) as col1
from t
group by key;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.