SQL计数2个相等的列并选择其他列

时间:2017-02-14 15:21:47

标签: sql sql-server count

我有两个单独的表,一个有空缺,另一个有空缺申请。我想选择一个新表,该表从空缺表中选择该表中的许多其他列,另一列计算这些空位的应用程序数。所以我的空缺表看起来像这样:

ID  Active  StartDate   JobID   JobTypeID   HoursPerWeek
1   1       2017-02-28  2       CE          0
2   1       2017-02-15  4       CE          40
3   1       2017-02-14  1       CE          40
4   1       2017-02-28  1       CE          48

我的应用程序表如下所示:

ID  VacancyID   Forename    Surname     EmailAddress        TelephoneNumber
1   1           John        Smith       jsmith@gmail.com    447777777777
2   2           John        Smith       jsmith@gmail.com    447748772641
3   2           John        Smith       jsmith@gmail.com    447777777777
4   2           John        Smith       jsmith@gmail.com    447700123456
5   4           John        Smith       jsmith@gmail.com    447400123569
6   4           John        Smith       jsmith@gmail.com    447400126547
7   4           John        Smith       jsmith@gmail.com    447555123654

我想要一个看起来像这样的表:

ID  Active  StartDate   JobID   HoursPerWeek    NumberOfApplicants
1   1       2017-02-28  2       0               1
2   1       2017-02-15  4       40              3
3   1       2017-02-14  1       40              0
4   1       2017-02-28  1       48              3

如何使用联接选择该表并计算VacancyID等于第一个空缺表的ID的申请人数?我试过了:

select Vacancy.ID, VacancyID, count(*) as NumberOfApplications from VacancyApplication
join Vacancy on Vacancy.ID=VacancyID
group by VacancyID, Vacancy.ID

这显然没有选择所有其他列,也没有选择ID 3,因为有0个应用程序 - 我希望ID 3在那里,值为0以及所有其他列。我该怎么做呢?我尝试过各种形式的分组和选择,但我对SQL很陌生,所以我不确定如何做到这一点。

4 个答案:

答案 0 :(得分:2)

使用RIGHT JOIN代替INNER JOIN并计算vacancyid表中的vacancyapplication列。对于不匹配的记录,您将计为0

SELECT v.id, v.Active, v.StartDate, v.JobID, v.HoursPerWeek
       Count(va.vacancyid) AS NumberOfApplications 
FROM   vacancyapplication va 
       RIGHT JOIN vacancy v 
               ON v.id = va.vacancyid 
GROUP  BY v.id, v.Active, v.StartDate, v.JobID, v.HoursPerWeek

开始使用Alias名称,使查询更具可读性

答案 1 :(得分:0)

使用left join和表别名:

select v.ID, count(va.VacancyID) as NumberOfApplications
from Vacancy v join
     VacancyApplication va
     on v.ID = va.VacancyID
group by v.ID;

您似乎想要所有列。您可以将它们包含在group by中。但是,相关子查询或outer apply更简单:

select v.*, va.cnt
from vacancy v outer apply
     (select count(*) as cnt
      from VacancyApplication va
      where v.ID = va.VacancyID
     ) va;

无论如何,这可能更有效,特别是如果你有VacancyApplication(VacancyID)的索引。

答案 2 :(得分:0)

希望,我理解你的问题。请尝试以下查询

select Vacancy.ID, VacancyID, count(*) as NumberOfApplications from           VacancyApplication
left join Vacancy on Vacancy.ID=VacancyID
group by VacancyID, Vacancy.ID

答案 3 :(得分:0)

您可以使用OVER子句将count用作窗口函数,从而消除了他对group by的需求:

SELECT v.ID,
       v.Active,
       v.StartDate,
       v.JobID,
       v.JobTypeID,
       COUNT(va.ID) OVER(PARTITION BY v.ID) HoursPerWeek
FROM Vacancy v
LEFT JOIN vacancyapplication va ON(v.ID = va.VacancyID)