在选择列表中获取Error无效,因为它不包含在聚合函数或GROUP BY子句中

时间:2015-04-03 12:22:02

标签: mysql

嗨,我是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

任何人都可以建议我查询,请提前致谢

1 个答案:

答案 0 :(得分:1)

如果您使用的是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;