CASE语句的SQL问题

时间:2015-03-10 15:49:21

标签: sql sql-server sql-server-2012-express

我试图调整以下声明:

    SELECT CASE WHEN OrganizationLevel < 2 THEN UPPER(JobTitle)
                    ELSE JobTitle END as 'Job Title', COUNT(BusinessEntityID) as 'number of employees'
    FROM HumanResources.Employee
    WHERE OrganizationLevel < 3 
    GROUP BY JobTitle, OrganizationLevel
    ORDER BY JobTitle ASC

我需要对其进行更改,以使JobTitle显示为&#39; SOMETHING ELSE&#39;当OrganisationLevel为1时。

我认为这对CASE声明进行一些小改动是一件简单的事情,因此JobTitle将会出现这样的情况:&#39; SOMETHING ELSE&#39;但它不允许我这样做,

2 个答案:

答案 0 :(得分:1)

   SELECT CASE WHEN OrganizationLevel < 2 THEN UPPER(JobTitle)
                    ELSE WHEN  OrganizationLevel =1 THEN 'SOMETHING ELSE' ELSE JobTitle END as 'Job Title', COUNT(BusinessEntityID) as 'number of employees'
    FROM HumanResources.Employee
    WHERE OrganizationLevel < 3 
    GROUP BY JobTitle, OrganizationLevel
    ORDER BY JobTitle ASC

答案 1 :(得分:1)

您需要在case

中使用相同的Group by语句
SELECT CASE
         WHEN OrganizationLevel = 1 THEN 'SOMETHING_ELSE'
         WHEN OrganizationLevel < 2 THEN Upper(JobTitle)
         ELSE JobTitle
       END                     AS 'Job Title',
       Count(BusinessEntityID) AS 'number of employees'
FROM   HumanResources.Employee
WHERE  OrganizationLevel < 3
GROUP  BY JobTitle,
          CASE
            WHEN OrganizationLevel = 1 THEN 'SOMETHING_ELSE'
            WHEN OrganizationLevel < 2 THEN Upper(JobTitle)
            ELSE JobTitle
          END
ORDER  BY JobTitle ASC