I want to use dates from a different table in the BETWEEN
inside the WHERE
clause.
How can I inject the dates? The query below works, but is much slower than using plain dates.
I've tried rewriting the query in numerous ways, as well as use CTEs, to no avail.
Is there a way to make this work faster?
select *
from (
select
ti.*,
si.anvat as vat,
cast(si.acName as nvarchar(255)) productNameOriginal,
cast(su.acName as nvarchar(255)) unit,
cast(ss.acName2 as nvarchar(255)) supplier,
historyStart,
historyEnd
from tenderItem ti
left join the_setitem si on si.acIdent = ti.sku
left join tHE_SetUM su on su.acUM = si.acUM
left join tHE_SetSubj ss on ss.acSubject = si.acSupplier
left join tender t on t.id = ti.tenderId
where tenderId = 1
) t1
left join (
select
acident sku,
sum(anQty) historyQuantity,
round(max(anRTPrice), 2) historyPrice
from the_moveitem mi
left join the_move m on m.ackey = mi.ackey
where
m.acDocType in (
'3000'
'3050'
)
and m.acreceiver = '11111'
and m.addate
between (select historyStart from tender where id = 1) -- <------ THIS PART
and (select historyEnd from tender where id = 1) -- <------ THIS PART
group by acident
) history on history.sku = t1.sku
Managed to solve it by using variables.
DECLARE @historyStart DATE;
SET @historyStart = (select historyStart from tender where id = @tenderId);
DECLARE @historyEnd DATE;
SET @historyEnd = (select historyEnd from tender where id = @tenderId);
--
and m.addate between @historyStart and @historyEnd
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.