我有一个查询使用Cross Apply。我需要运行多个[Quote Id]的查询。这是我原来的疑问:
SELECT distinct
[Reports].[Quote_Header_Details_vw].[Quote_Id]
,[Reports].[Quote_Header_Details_vw].[Quote_Created]
,[Reports].[Quote_Header_Details_vw].[Com_Product]
,[Reports].[Quote_Header_Details_vw].[Ene_Product]
,b.[Completed]
,b.[Description]
FROM [Reports].[Quote_Header_Details_vw]
CROSS APPLY (SELECT Top 1
Core.Job.[Completed]
,Core.Job.[Description]
FROM Core.Job
WHERE [Quote_Header_Details_vw].[Quote_Created]>=Core.Job.[Completed]
And Core.Job.[Description] like '%'+[Reports].[Quote_Header_Details_vw].[Ene_Product]
Order by Core.Job.[Completed] DESC) AS b
据我所知,在Cross Apply语句中花费了大量时间进行Top 1操作。查询当前需要超过40秒才能运行单个引用ID,并且随着Core.Job表的增长,查询将变得越来越慢。因此,对我来说这不是一个可行的解决方案。
有更快更好的方法吗?非常感谢你。请注意,[Quote_Header_Details_vw]和[Core.Job]表之间没有任何关系,即无法加入它们。
答案 0 :(得分:-1)
只需将它们放入变量中,然后使用select
中的变量declare @dd1 varchar(20);
declare @dd2 varchar(20);
select top (1) @dd1 = [name], @dd2 = [dispName]
from [table]
order by [name] desc;
select @dd1, @dd2;
OP需要具体细节
declare @dd1 varchar(20);
declare @dd2 varchar(20);
SELECT Top (1)
@dd1 = Core.Job.[Completed]
, @dd2 = Core.Job.[Description]
FROM Core.Job
WHERE [Quote_Header_Details_vw].[Quote_Created] >= Core.Job.[Completed]
And Core.Job.[Description] like '%'+[Reports].[Quote_Header_Details_vw].[Ene_Product]
Order by Core.Job.[Completed] DESC;
SELECT distinct
[Reports].[Quote_Header_Details_vw].[Quote_Id]
,[Reports].[Quote_Header_Details_vw].[Quote_Created]
,[Reports].[Quote_Header_Details_vw].[Com_Product]
,[Reports].[Quote_Header_Details_vw].[Ene_Product]
,@dd1 as [Completed]
,@dd2 as [Description]
FROM [Reports].[Quote_Header_Details_vw];
或尝试
select * from
(
SELECT r.[Quote_Id]
,r.[Quote_Created]
,r.[Com_Product]
,r.[Ene_Product]
,b.[Completed]
,b.[Description]
,row_number() over (partition by r.[Quote_Id] order by b.[Completed] desc) as rn
FROM [Reports].[Quote_Header_Details_vw] r
join Core.Job b
on r.[Quote_Created] >= b.Job.[Completed]
And b.[Description] like '%'+r.[Ene_Product]
) tt
where tt.rn = 1