首先抱歉模糊的标题不知道如何解释它。在下面的查询中,我想把事件从'truck1'参加的地方拉出来。不仅仅是自己,而是当其他车辆参加时。我确定它的东西是直接的,但无法解决。
select
i.incident_number
Vehicles,
countofvehicles
FROM
(
SELECT
i.Incident_Number,
array_agg(ir.RESOURCE) as vehicle,
count(ir.RESOURCE) as countofvehicles
FROM INCIDENT as i
JOIN RESOURCE as ir on i.Incident_Number = ir.Incident_Number
--WHERE ir. like '%Truck1%'
GROUP BY i.Incident_Number) i
结果
incident_Number vehicle countofvehicle
1 car1,car2,bike1 3
2 car1,car2,truck1 3
3 truck1 1
4 car1 1
如果我想看看卡车1只参加了哪些事故,那么使用WHERE ir.RESOURCE就像'%truck1%只会带回事故3号而不是事故2,它与其他车辆一起参加。我怎么能绕过这个呢?
由于
答案 0 :(得分:0)
您不需要子查询,只需having
子句:
SELECT i.Incident_Number,
array_agg(ir.RESOURCE) as vehicle,
count(ir.RESOURCE) as countofvehicles
FROM INCIDENT i JOIN
RESOURCE ir
ON i.Incident_Number = ir.Incident_Number
GROUP BY i.Incident_Number
HAVING SUM(CASE WHEN ir.RESOURCE like '%truck1% THEN 1 ELSE 0 END) > 1;
事实上,您可能也不需要join
,因为您从INCIDENT
获取的唯一字段也位于RESOURCE
中:
SELECT ir.Incident_Number,
array_agg(ir.RESOURCE) as vehicle,
count(ir.RESOURCE) as countofvehicles
FROM RESOURCE ir
GROUP BY ir.Incident_Number
HAVING SUM(CASE WHEN ir.RESOURCE like '%truck1% THEN 1 ELSE 0 END) > 1;