SQL 查询 distinct with case 函数
SQL query distinct with case function
我有以下数据:
ID Owner
--------
01 Sarah
01 Andrew
02 Sarah
03 Andrew
04 Andrew
04 Sarah
05 Andrew
我想获得以下输出:
ID Grouped_Owners
---------
01 Andrew and Sarah
02 Sarah
03 Andrew
04 Andrew and Sarah
05 Andrew
我试过这个查询(以及类似方法的其他迭代):
select
distinct(id)
, case
when count(id) > 1 then 'Andrew and Sarah'
else owner
end as Grouped_Owners
from Ads
group by id, Owner
order by id
...但我无法得到结果。我 怀疑 我可能需要使用 windowing/partition 函数,但这似乎有点过分了。我在网上搜索过,但我似乎找不到适合这个用例的任何内容:/
我相信这对这里的专家来说是一个非常快速的答案! :) 谢谢!
您需要将 GROUP_CONCAT 与 GROUP BY
一起使用:
SELECT
ID,
GROUP_CONCAT(Owner SEPARATOR ' and ') AS Grouped_Owners
FROM Ads
GROUP BY ID
ORDER BY ID
我有以下数据:
ID Owner
--------
01 Sarah
01 Andrew
02 Sarah
03 Andrew
04 Andrew
04 Sarah
05 Andrew
我想获得以下输出:
ID Grouped_Owners
---------
01 Andrew and Sarah
02 Sarah
03 Andrew
04 Andrew and Sarah
05 Andrew
我试过这个查询(以及类似方法的其他迭代):
select
distinct(id)
, case
when count(id) > 1 then 'Andrew and Sarah'
else owner
end as Grouped_Owners
from Ads
group by id, Owner
order by id
...但我无法得到结果。我 怀疑 我可能需要使用 windowing/partition 函数,但这似乎有点过分了。我在网上搜索过,但我似乎找不到适合这个用例的任何内容:/
我相信这对这里的专家来说是一个非常快速的答案! :) 谢谢!
您需要将 GROUP_CONCAT 与 GROUP BY
一起使用:
SELECT
ID,
GROUP_CONCAT(Owner SEPARATOR ' and ') AS Grouped_Owners
FROM Ads
GROUP BY ID
ORDER BY ID