嗨,我是 Sql 新手,这里有这样的表
ID | Name
1 a
2 a
3 h
4 e
5 d
6 d
想要的输出应该是
name | IDS
a 1,2
d 5,6
我尝试过但抛出错误
select distinct ID, (select CAST(t.ID AS VARCHAR(10)) +','
from tbl t
where t.ID=tb.ID
for xml path('')) name
from tbl tb
group by name
以下错误:
invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause
任何人都可以建议我写一份查询吗,请提前致谢
最佳答案
如果您使用的是 MySQL
select name, group_concat(t.id)
from tbl tb
group by name
having count(*) > 1;
在 SQL Server 中:
select name,
stuff((select ',' + CAST(t.ID AS VARCHAR(255))
from tbl t
where t.name = tb.name
for xml path('')
), 1, 1, '') name
from tbl tb
group by name
having count(*) > 1;
关于mysql - 选择列表中出现无效错误,因为它不包含在聚合函数或 GROUP BY 子句中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29432119/