为什么我的SQL查询不起作用?

时间:2014-07-09 11:22:51

标签: sql sql-server

我写了一个查询来从SQL Server中检索一些数据:

 declare @Orig varchar(10);
 set @Orig = 205801;

 declare @ServiceCode varchar(10);
 set @ServiceCode = 'PEJ';

 SELECT  
     ContentId, COALESCE(Content, [Text]) as Content, COUNT(*) as [count]
 FROM 
     [SendArchive_92].[dbo].[9210]
 INNER JOIN
     [VSServices].[dbo].[ServiceContents] ON [VSServices].[dbo].[ServiceContents].[Id] =[SendArchive_92].[dbo].[9210].[ContentId]
 WHERE 
     [SendArchive_92].[dbo].[9210].Orig = @Orig 
     AND [SendArchive_92].[dbo].[9210].ServiceCode = @ServiceCode 
 GROUP BY 
     [VSServices].[dbo].[ServiceContents].[Text], [SendArchive_92].[dbo].[9210].ContentId

但是我收到了错误

  

列'SendArchive_92.dbo.9210.Content'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。

当我在查询中删除COALESCE时,它运行正常,问题是什么?

1 个答案:

答案 0 :(得分:1)

首先,使用表别名更容易编写和读取查询:

SELECT t9.ContentId, COALESCE(t9.Content, sc.[Text]) as Content, COUNT(*)as [count]
FROM [SendArchive_92].[dbo].[9210] t9 inner join
     [VSServices].[dbo].[ServiceContents] s
     on sc.[Id] = t9.[ContentId]
where t9.Orig = @Orig and sc = @ServiceCode 
group by sc.[Text], t9.ContentId;

问题在于ContentIdContent条款中没有group by