我正在尝试聚合一些车祸,每次崩溃都会被赋予一个唯一的ID,并被分配到一个或多个街道段(一个段就像一个街区),所以:
crashid | segment1 | segment2 | segment3 | segment4
---------------------------------------------------
001 1 2 3 4
002 4 5 6 7
003 4
第二个表包含一个“走廊”,它是一组段ID。走廊是不相交的,即不包含重叠的街道段:
corridor | segmentid
--------------------
A 4
A 7
A 10
B 11
B 12
...
地图看起来像:
3| 5 | 8|
| | |
1---|--4--|--7--|--10--
| | |
2| 6| 9|
所以,我想得到每个走廊发生的崩溃总和。对于走廊A,这是包含段4,7或10的崩溃ID的计数。
答案 0 :(得分:0)
select count(*)
from
(
select crashid
from cor
join crash on crash.segement1 = cor.segmentid
where cor.corridor = @incorridor
union all
select crashid
from cor
join crash on crash.segement2 = cor.segmentid
where cor.corridor = @incorridor
union all
select crashid
from cor
join crash on crash.segement3 = cor.segmentid
where cor.corridor = @incorridor
union all
select crashid
from cor
join crash on crash.segement4 = cor.segmentid
where cor.corridor = @incorridor
)