如何使用内容选择列的特定名称?

时间:2014-04-25 14:43:51

标签: sql sql-server

您好我的SQL Server 2012存在问题,

SELECT e.especes,COUNT(*) AS [nombre de sujets],
    STUFF((SELECT  ',' + ' ' + a.nom 
              FROM  animal a,espece e
              where e.IDESPECE = a.IDESPECE
              FOR XML PATH (''))
              , 1, 1, '')  AS noms
    INTO statEspece 
    from espece e,animal a 
    WHERE e.IDESPECE = a.IDESPECE 
    GROUP BY a.IDESPECE, e.especes;

即使我试着把这一行:

  

其中e.IDESPECE = a.IDESPECE

名称列填充了dbo.animal.nom的所有动物。

输出如下:

Animal  Number   Names
Tigre   2   Tigrou, Chita, Chloe, Jumbo, Zaza, Coco, Kahn, King
Lion    1   Tigrou, Chita, Chloe, Jumbo, Zaza, Coco, Kahn, King
Zèbre   1   Tigrou, Chita, Chloe, Jumbo, Zaza, Coco, Kahn, King
Singe   2   Tigrou, Chita, Chloe, Jumbo, Zaza, Coco, Kahn, King
other   1   Tigrou, Chita, Chloe, Jumbo, Zaza, Coco, Kahn, King
other   1   Tigrou, Chita, Chloe, Jumbo, Zaza, Coco, Kahn, King

有人可以解释一下为什么它会将数据库中的所有名字都归还给我吗?

1 个答案:

答案 0 :(得分:1)

试试这个:

SELECT e.especes,COUNT(*) AS [nombre de sujets],
STUFF((SELECT  ',' + ' ' + a1.nom 
          FROM  animal a1,espece e1
          where e1.IDESPECE = a1.IDESPECE AND a1.IDESPECE=a.IDESPECE
          FOR XML PATH (''))
          , 1, 1, '')  AS noms
INTO statEspece 
from espece e,animal a 
WHERE e.IDESPECE = a.IDESPECE 
GROUP BY a.IDESPECE, e.especes;