簡體   English   中英

在選擇列表中得到錯誤無效,因為它不包含在聚合函數或GROUP BY子句中

[英]getting Error invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM