我遇到了一个sql代码,我需要按照以下方式获取数据(我希望我能解释得足够好): 我的数据库中有三个表:
Table 1 is filled with traffic accidents(VKL_NUMBER and TIME)
Table 2 is filled with the locations of the accidents and the closest weather station (VKL_NUMBER, LOCATION and STN_NUMBER )
Table 3 is filled with weather data and the weather station where it came from(STN_NUMBER, TIME, WEATHER_TYPE)
我需要计算下雨的事故数量。 表格的关键是:
From 1 to 2: VKL_NUMBER(accident number)
From 2 to 3: STN_NUMBER (weather station number)
我怎样才能获得当时最接近事故的风雨类型 喜欢:
Count accidents where it rains at the closest weatherstation.
了解更多信息:
The accidents table has VKL_NUMBER(FK to the locations table) TIME(HHMM format) and DATE(YYMMDD format)
The locations table has VKL_NUMBER(FK to accidents), LOCATION(not important for this question) and STN_NUMBER(FK to the weather table)
The weather table had STN_NUMBER(FK to locations table), WEATHERTYPE("rain","snow","hail" ), TIME(HHMM format) and DATE(YYMMDD format)
答案 0 :(得分:1)
/* apparently you'll need to combine and cast the <date + time> values */
select count(case when weather.weathertype = 'rain' then 1 end)
from
(
select
accidents.vkl_number,
min(<accidents.date + accidents.time>) as time_of_accident,
min(weather.stn_number) as stn_number,
max(timestampdiff(minute,
<weather.date + weather.time>,
<accidents.date + accidents.time>
)) as differential
from
t1 accidents inner join t2 accident_locations
on accident_locations.vkl_number = accidents.vkl_number
inner join t3 weather
on weather.stn_number = accident_locations.stn_number
and weather.time <= accidents.time
group by accidents.vkl_number
) closest
inner join t3 weather
on weather.stn_number = closest.stn_number
and date_add(
<weather.date + weather.time>,
interval differential second
) = closest.time_of_accident
我假设你想要在事故发生之前的车站时间。打破关系是一个重大的复杂因素,我们需要更多关于您所需的匹配逻辑的信息。