首先很抱歉标题模糊,不知道该怎么解释。在下面的查询中,我想找出“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

如果我想查看只有truck1参与的事件,则使用where ir.RESOURCE(如'%truck1%')只会返回第3个事件,而不会返回与其他车辆一起参与的第2个事件。我怎样才能避开这个?
谢谢

最佳答案

不需要子查询,只需要一个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;

10-06 06:48