带有条件显示的SQL案例

时间:2015-03-19 16:24:19

标签: sql sql-server tsql

我正在尝试编写一个查询,为每个'申请人'返回1行,如果employeeIds的数量为1,则会显示申请人的employerId,否则会返回该列上的字符串“多个应用程序“。请看下面,我正在使用MSSQL。有人能引导我走向正确的方向吗?

    Table: Applicant

    ID | FirstName | LastName
    ----------------------------
    01 | John      | Smith
    02 | Mark      | Doe
    03 | George    | Washington



    Table: Employer

    ID | ApplicantId | EmployerId
    ----------------------------
    01 | 01          | 100
    02 | 01          | 103
    03 | 02          | 101
    04 | 03          | 106


    Desired Output:

    FirstName | LastName   | Employer
    ---------------------------------
    John      | Smith      | Multiple Applications
    Mark      | Doe        | 101
    George    | Washington | 106

谢谢!

3 个答案:

答案 0 :(得分:2)

您可以使用简单的分组,并在只有一个项目时使用MIN来获取值:

SELECT Applicant.FirstName, Applicant.Surname, 
    CASE WHEN COUNT(Employer.ID) = 1 
        THEN CAST(MIN(Employer.Id) AS varchar(10))
        ELSE 'Multiple Applications' 
    END AS Employer
FROM Applicant
    INNER JOIN Employer ON Applicant.Id = Employer.Id
GROUP BY Applicant.Id, Applicant.FirstName, Applicant.Surname

答案 1 :(得分:1)

select
    min(FirstName) as FirstName,
    min(LastName) as LastName,
    case
        when count(*) > 1 then 'Multiple Applications'
        else cast(min(EmployerId) as varchar(11))
    end as Employer
from Applicant as a inner join Employer as e on e.ApplicantId = a.Id
group by a.Id

您当然可以拥有多个具有相同名称的申请人,尤其是姓氏。因此,如果不对申请人ID进行分组,您就不希望对这些列进行分组。

许多人喜欢添加额外的组列,以避免在1:M连接的一侧对列进行虚拟聚合表达。 (而其他平台允许您在没有聚合的情况下引用常量或“功能相关”列。)我个人认为该方法掩盖了查询的意图。这些额外的分组可能会改变查询计划和/或性能。

这种情况很有意思,因为我们必须在case表达式中使用虚拟聚合。因此,在第一个和最后一个名称列中反映它也更有意义。

答案 2 :(得分:0)

Select *
 ,  CASE WHEN 
        (Select COUNT(ApplicantId) From Employer 
        Where Employer.ApplicantId = Applicant.ID) =  1 
    THEN CAST(Applicant.ID AS varchar) 
    ELSE 'Multiple Applications' ENd AS [Applicant]
From Applicant