寻找有关将多个SQL查询合并到多部分内部连接语句中的建议。
我有以下三个表(表:列):
访问表:pid,visit_date,visit_start_datetime,visit_end_datetime,visit_id,visit_type,visit_length,visit_rating
CondTable :pid,cond_date,cond_datetime,cond_id,cond_type,cond_length,cond_rating
产品表:pid,prod_id,prod_date,prod_start_datetime,prod_end_datetime,prod_rating,prod_price
我有以下原子SQL查询:
instead.
让我们调用第一个查询(select pid, visit_date, visit_start_datetime, visit_end_datetime
from VisitTable
where visit_id = XYZ AND visit_start_datetime > '01/01/2009'
select pid, cond_date, cond_datetime
from CondTable
where cond_id in (ABC, DEF, GHI)
select pid, prod_date, prod_start_datetime, prod_end_datetime
from ProdTable
where prod_id in (123, 456, 789)
),第二个查询(Temp1
)和第三个查询(Temp2
)的结果。
我想在Temp3
的{{1}}内将Temp1
与Temp2
内部联接,即pid
在范围{ Temp1.visit_start_datetime <= Temp2.cond_datetime <= Temp1.visit_end_datetime
的{1}}。我们称这个联接Temp2.cond_datetime
的结果。
然后,我想获取此结果([Temp1.visit_start_datetime, Temp1.visit_end_datetime]
)并与pid
上的Temp4
进行内部连接,其中Temp4
在Temp3
的范围内。 / p>
问题:
我尝试了以下语法,但这是不正确的:
pid
在第一个原子SQL查询中,我最初尝试将Temp3.prod_start_datetime
和[Temp1.visit_start_datetime, Temp1.visit_end_datetime]
子句一起使用,但是出现错误,提示“ visit_date”是一个整数。然后,我尝试使用select pid, visit_date, visit_start_datetime, visit_end_datetime
from VisitTable
where visit_id = XYZ AND visit_start_datetime > '01/01/2009'
left join
(select pid, cond_date, cond_datetime
from CondTable
where cond_id in (ABC, DEF, GHI)) Temp2 on Temp2.pid = VisitTable.pid
where Temp2.cond_datetime between VisitTable.visit_start_datetime and VisitTable.visit_end_datetime
left join
(select pid, prod_date, prod_start_datetime, prod_end_datetime
from ProdTable
where prod_id in (123, 456, 789)) Temp3 on Temp3.pid = VisitTable.pid
where Temp3.prod_start_datetime between VisitTable.visit_start_datetime and VisitTable.visit_end_datetime
,它接受了条件WHERE
。为什么会发生这种情况,反正我可以改用visit_date
吗?
构造此查询后,如何按日期分组并计算每个日期出现的条目数?
谢谢!
答案 0 :(得分:2)
请尝试使用以下SQL,您的日期格式无法通过SQL查询理解。
select Temp1.* from
(
select pid, visit_date, visit_start_datetime, visit_end_datetime
from VisitTable
where visit_id = XYZ AND visit_start_datetime > '2009-01-01'
) as Temp1 inner join
(
select pid, cond_date, cond_datetime
from CondTable
where cond_id in (ABC, DEF, GHI)
) as Temp2 on Temp1.pid = Temp2.pid
and Temp1.visit_start_datetime <= Temp2.cond_datetime and Temp2.cond_datetime <= Temp1.visit_end_datetime
inner join
(
select pid, prod_date, prod_start_datetime, prod_end_datetime
from ProdTable
where prod_id in (123, 456, 789)
) as Temp3 on Temp1.pid = Temp3.pid
and Temp1.visit_start_datetime <= Temp3.prod_start_datetime and Temp3.prod_start_datetime <= Temp1.visit_end_datetime