我有我为客户需要的查询编写的这段代码。结果正是我们所需要的,但是我得到了一些非常长的响应时间。查询的第一部分比第二部分花费更长的时间,而查询本身并没有太大的不同。基本上,它们是两个不同的查询,我使用 UNION ALL 将它们合并为一个。
任何反馈都会很好地简化这一点。谢谢
Select * from
(
Select b.Storage_Loc_Nbr as locNbr, b.CurrentLoadCount,b.MMM_Id_Nbr,
(SELECT count(Load_ID) as LoadCount
FROM t_load c
WHERE b.MMM_Id_Nbr=c.MMM_Id_Nbr
and
QC_Status_Code like 'R%' and mmm_Facility_Code ='MC' and Active_Status_Ind='A'
and
b.Storage_Loc_Nbr <> c.Storage_Loc_Nbr)as OtherLocCount
FROM
(
SELECT * FROM
(
SELECT t_load.Storage_Loc_Nbr,
Count(t_Load.Load_Id) AS CurrentLoadCount,
t_load.MMM_Id_Nbr,
t_Storage_Location.Storage_Loc_Type_Code
FROM t_Load LEFT JOIN t_Storage_Location ON t_Load.Storage_Loc_Nbr = t_Storage_Location.Storage_Loc_Nbr
WHERE (
((t_load.MMM_Id_Nbr) between '702004%' and '702011%')
AND ((t_Load.Active_Status_Ind)='A')
AND ((t_Load.QC_Status_Code) Like 'R%')
AND ((t_Load.MMM_Facility_Code)='MC')
AND ((t_Storage_Location.Storage_Loc_Type_Code)='CD')
)
GROUP BY t_load.MMM_Id_Nbr,
t_load.Storage_Loc_Nbr,
t_Storage_Location.Storage_Loc_Type_Code
HAVING
Count(t_Load.Load_Id)<=1
)
as a
)
as b
)
as c
Group By
locNbr,CurrentLoadCount, MMM_Id_Nbr, OtherLocCount
having OtherLocCount>0
UNION ALL
Select * from
(
Select b.Storage_Loc_Nbr as locNbr, b.CurrentLoadCount,b.MMM_Id_Nbr,
(SELECT count(Load_ID) as LoadCount
FROM t_load c
WHERE b.MMM_Id_Nbr=c.MMM_Id_Nbr
and
QC_Status_Code like 'R%' and mmm_Facility_Code ='MC' and Active_Status_Ind='A'
and
b.Storage_Loc_Nbr <> c.Storage_Loc_Nbr)as OtherLocCount
FROM
(
SELECT * FROM
(
SELECT t_load.Storage_Loc_Nbr,
Count(t_Load.Load_Id) AS CurrentLoadCount,
t_load.MMM_Id_Nbr,
t_Storage_Location.Storage_Loc_Type_Code
FROM t_Load LEFT JOIN t_Storage_Location ON t_Load.Storage_Loc_Nbr = t_Storage_Location.Storage_Loc_Nbr
WHERE (
((t_load.MMM_Id_Nbr) between '702004%' and '702011%')
AND ((t_Load.Active_Status_Ind)='A')
AND ((t_Load.QC_Status_Code) Like 'R%')
AND ((t_Load.MMM_Facility_Code)='MC')
AND ((t_Storage_Location.Storage_Loc_Type_Code)<>'CD') AND
((t_load.Storage_Loc_Nbr)<>'clc' AND (t_load.Storage_Loc_Nbr)<>'WHLEAD') AND
(
((t_load.Storage_Loc_Nbr) Like '%A')
OR((t_load.Storage_Loc_Nbr) Like '%B')
OR ((t_load.Storage_Loc_Nbr) Like '%C')
OR ((t_load.Storage_Loc_Nbr) Like '%D')
OR ((t_load.Storage_Loc_Nbr) Like '%E'))
)
GROUP BY t_load.MMM_Id_Nbr,
t_load.Storage_Loc_Nbr,
t_Storage_Location.Storage_Loc_Type_Code
HAVING
Count(t_Load.Load_Id)<=1
)
as a
)
as b
)
as c
Group By
locNbr,CurrentLoadCount, MMM_Id_Nbr, OtherLocCount
having OtherLocCount>0
Order by
LocNbr