我需要列出存在活跃员工的数据库中的所有城市。如果城市存在于多个州,我想将州名添加到其中。所以我尝试做类似的事情:
SELECT Locations.LocationID,
CASE
WHEN Locations.City IS NOT DISTINCT
THEN Locations.City + '(' + ISNULL(Locations.State,'') + ')'
ELSE Locations.City
END as LocationDescription
FROM Locations
INNER JOIN Employees on Locations.LocationID = Employees.LocationID
WHERE Employees.Active=1
ORDER BY LocationDescription
显然,这不是正确的语法,我使用的是DISTINCT,但不知道如何解决这个问题。
答案 0 :(得分:2)
我会选择每次添加状态,但是,如果您真的想这样做,可以使用GROUP BY
和IN
条款......
WHEN Locations.City IN (SELECT Locations.City FROM Location GROUP BY City HAVING COUNT(*) > 1)
答案 1 :(得分:2)
你可以使用相关的子查询来完成它,但是不总是更容易附加状态吗?它也会使输出更加一致......
可能有更聪明的方法,但这应该有用。
SELECT l.LocationID,
CASE
WHEN (SELECT COUNT(City) FROM Locations WHERE L.city = city) > 1
THEN l.City + '(' + ISNULL(l.State,'') + ')'
ELSE l.City
END as LocationDescription
FROM Locations L
INNER JOIN Employees on l.LocationID = Employees.LocationID
WHERE Employees.Active=1
ORDER BY LocationDescription