GROUP BY子句给出错误

时间:2016-07-05 08:24:24

标签: sql sql-server

我有两张桌子。第一个是空缺表

空缺表:

╔════════════╦═════════════╗
║ VacancyId  ║ title       ║
╠════════════╬═════════════╣
║     1      ║  Vac1       ║
║     2      ║  Vac2       ║
║     3      ║  Vac3       ║
╚════════════╩═════════════╝

,第二个是空缺申请表

空缺申请表:

╔══════════════════════╦═══════════╦══════════════╦══════════════════╗
║          id          ║ VacancyId ║   source     ║ Application Date ║
╠══════════════════════╬═══════════╬══════════════╬══════════════════╣
║           1          ║     1     ║      abc     ║   2009-01-01     ║
║           2          ║     1     ║      def     ║   2009-01-02     ║
║           3          ║     2     ║      abc     ║   2010-01-02     ║
║           4          ║     3     ║      def     ║   2011-02-02     ║
║           5          ║     2     ║      abc     ║   2010-03-04     ║
║           6          ║     1     ║      def     ║   2009-04-07     ║
╚══════════════════════╩═══════════╩══════════════╩══════════════════╝

正如您在空缺表中可以看到的那样,空缺申请表中有多个条目。此表中还有另一列名为source。我想算不上。每个空缺的申请来源。

预期结果

╔════════ ╦══════  ╦═════════════╗
║ vacancy ║ source ║ No. Of App  ║
╠════════ ╬══════  ╬═════════════╣
║   vac1  ║ ABC    ║     1       ║
║   vac1  ║ DEF    ║     2       ║
║   vac2  ║ abc    ║     2
    vac3  ║ def          1
╚════════ ╩══════  ╩═════════════╝

因为我写了这个查询

select v.title,  isnull(nullif(va.source,''), 'Unknown') source, COUNT(va.source) apps  from [VacancyApplication] as va inner join [Vacancy] as v on v.id= va.vacancyid     group by source

但它给我一个错误

  

Vacancy.title'在选择列表中无效,因为它不是   包含在聚合函数或GROUP BY子句中。

如果我排除空缺职位,那么它会给出结果

select isnull(nullif(source,''), 'Unknown') source, COUNT(source) apps 
    from [MyPeople_DataVersion2].[dbo].[VacancyApplication]
    where vacancyid in (select v.id  from [MyPeople_DataVersion2].[dbo].[Vacancy] as v where v.deleted=0 )  and deleted = 0
    group by source

但后来我不知道空缺的名称......我认为它将多个空缺来源(具有相同的来源名称)结合在一起。

你可以建议吗

4 个答案:

答案 0 :(得分:2)

请尝试以下方法:

SELECT v.title,  isnull(nullif(va.source,''), 'Unknown') source, COUNT(va.source) apps
  FROM [VacancyApplication] AS va
  INNER JOIN [Vacancy] AS v on v.id= va.vacancyid
  GROUP BY v.title,  isnull(nullif(va.source,''), 'Unknown')

答案 1 :(得分:1)

您应该通过

将v.title添加到组中
Select v.title,  
isnull(nullif(va.source,''), 
'Unknown') source, 
COUNT(va.source) apps  
from [VacancyApplication] as va inner join [Vacancy] as v on v.id= va.vacancyid     
group by v.title,
isnull(nullif(va.source,''), 'Unknown')

答案 2 :(得分:1)

正如错误消息显示的那样。只需将标题添加到group by

即可
select v.title,  isnull(nullif(va.source,''), 'Unknown') source, COUNT(va.source) apps 
from [VacancyApplication] as va inner join [Vacancy] as v on v.id= va.vacancyid
group by source, v.title

答案 3 :(得分:1)

考虑聚合正在做什么,遍历行,在组上创建唯一的多列键并应用聚合。它应该用未指定的列做什么?

通过

将v.title添加到组中