mysql - 选择列表中出现无效错误,因为它不包含在聚合函数或 GROUP BY 子句中

标签 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

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

最佳答案

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

相关文章:

php - symfony 1.4 中的性能问题

python - 如何将Python程序中的数据间隔插入MySQL数据库

php - 选择自引用表上未被任何其他行指向的行

mysql - 组查询不支持mysql 8;

mysql - 在 Yii 中对 CHtml::listData 下拉列表进行排序

jquery 数据表 : fetch next 25 rows from databse on next page button of jQuery datatable

上传图片的php脚本不起作用

mysql - 使用连接计算列的总和

mysql - 这个查询语句怎么用sql写出来呢?

mysql获取一个表中的行,另一表中的日期为一年,但不是另一年