我有一个完整的大脑屁时刻,所以我想我会在这里问。 我有3个看起来像这样的表
设备表
EquipmentID | LocationID
-------------------------
1 | 2
2 | 2
3 | 1
4 | 2
5 | 3
6 | 3
位置表
LocationID | LocationName
--------------------------
1 | Pizza Hut
2 | Giordanos
3 | Lou Malnati's
服务表
LocationID | EquipmentID | Status
-----------------------------------
2 | 1 | Serviced
2 | 2 | Not Yet Serviced
2 | 4 | Not Yet Serviced
3 | 5 | Serviced
我需要一种方法来列出已经维修过一台或多台设备的所有地点,但并非该地点的所有设备都已经过维修。
因此,对于上面的示例,它将返回以下结果
LocationID | ServicedEquipmentID | NotServicedEquipmentIDS | LocationStatus
------------------------------------------------------------------------------
2 | 1 | 2, 4 | Partially Serviced
3 | 5 | 6 | Partially Serviced
感谢您的帮助!
答案 0 :(得分:3)
此查询将为您提供所需的位置状态,但不是单个设备状态:
SELECT [LocationId]
,[LocationId]
,CASE ( [IsServiced] + [IsNotServiced] )
WHEN 0 THEN 'Not Serviced'
WHEN 1 THEN 'Partially Serviced'
WHEN 2 THEN 'Serviced'
END [LocationStatus]
FROM ( SELECT [l].[LocationId]
,[e].[LocationId]
,CASE [s].[Status]
WHEN 'Serviced' THEN 1
ELSE 0
END [IsServiced]
,CASE [s].[Status]
WHEN 'Not Yet Serviced' THEN 1
ELSE 0
END [IsNotServiced]
FROM [Location] l
INNER JOIN [Equipment] e ON [l].[LocationId] = [e].[LocationId]
INNER JOIN [Service] s ON [l].[LocationId] = [s].[LocationId]
AND [e].[EquipmentId] = [s].[EquipmentId]
) x
要将已经/未被服务的设备ID的逗号分隔列表添加到结果集,您将需要某种类型的CONCAT功能。 UDF,CLR或递归CTE(我现在没时间写这个 - here's a link)。