我对以下查询有疑问。我有两个桌子。表Orderheader和表已购买。例如,我执行的第一个查询给了我两个日期。基于这两个日期,我需要找到生产数据,并且基于生产数据,我需要找到购买数据,并将这些数据组合在一起。可以说我做了以下事情:
Select Lotdate From Orderheader where orhsysid = 1
这将导致两行:“ 2019-02-05”和“ 2019-02-04”。现在,我需要做两件事:我需要两个使用此结果集运行两个查询。第一个很简单;使用返回的日期并像这样获得A列的总和:
Select date, SUM(Amount) from Orderheader where date = Sales.date() [use the two dates here]
第二个要稍微复杂一点,我需要根据两个日期找到最后一天买了东西。生产是日常工作,因此Productiondate = Sales.date()-1。但是Bought源自Productionday,而不是每天,因此对于每个Productionday,它都需要找到最后一个Boughtday。所以我不能说日期= Orderheader.date。我需要做类似的事情:
Select date, SUM(Amount)
FROM Bought
WHERE date = (
SELECT top 1 date
FROM Bought
WHERE date < Orderheader.date)
但是两次,我都得到了两个约会。 这需要产生一张表给我:
Bought.date, Bought.SUM(AMOUNT), Orderheader.date, Orderheader.SUM(AMOUNT)
全部基于我从Sales表的第一个查询获得的Lotdate的可能倍数。
我已经使用连接和嵌套查询进行了一段时间的努力,但是我似乎无法弄清楚!
示例示例:
SELECT CONVERT(date,ORF.orfDate) as Productiedatum, SUM(orlQuantityRegistered) as 'Aantal'
FROM OrderHeader ORH
LEFT JOIN OrderFrame ORF ON ORH.orhFrameSysID = ORF.orfSysID
LEFT JOIN OrderLine ORL ON ORL.orhSysID = ORH.orhSysID
LEFT JOIN Item ON Item.itmSysID = ORL.orlitmSysID
where CONVERT(date,ORF.orfDate) IN
(
SELECT DISTINCT(CONVERT(date, Lot.lotproductiondate)) as Productiedatum
FROM OrderHeader ORH
LEFT JOIN Registration reg ON reg.regorhSysID = ORH.orhSysID
LEFT JOIN StockRegistration stcreg ON stcreg.stcregRegistrationSysID = reg.regSysID
LEFT JOIN Lot ON Lot.lotSysID = stcregSrclotSysID
WHERE ORH.orhSysID = 514955
AND regRevokeRegSysID IS NULL
AND stcregSrcitmSysID = 5103
)
AND ORL.orlitmSysID = 5103
AND orldirSysID = 2
AND NOT orlQuantityRegistered IS NULL
GROUP BY Orf.orfDate
示例输出:
Productiedatum Aantal
2019-02-05 20
2019-02-06 20
在这里,我使用嵌套的子查询从“生产”(订单标题)获取结果,因为我只能使用date = date。我在“销售”部分中苦苦挣扎,需要在其中查找最后一个日期,并在“销售”表中使用这些日期来获取该日期的总和。
预期输出:
Productiedatum Aantal Boughtdate Aantal
2019-02-04 20 2019-02-01 55
2019-02-05 20 2019-02-04 60
答案 0 :(得分:2)
尝试一下。
IF OBJECT_ID('tempdb..#Production') IS NOT NULL DROP TABLE #Production
IF OBJECT_ID('tempdb..#Bought') IS NOT NULL DROP TABLE #Bought
CREATE table #Production(R_NO int,ProductionDate datetime,ProductionAmount float)
CREATE table #Bought(R_NO int,Boughtdate datetime,Boughtamount float)
insert into #Production(ProductionDate,ProductionAmount,R_NO)
select p.date ProductionDate,sum(Amount) ProductionAmount,row_number()over (order by p.date) R_NO
from Production P
join Sales s on p.date=S.date-1
where orhsysid=1
group by p.date
declare @loop int,@ProdDate datetime
select @loop =max(R_NO) from #Production
while (1<=@loop)
begin
select @ProdDate=ProductionDate from #Production where r_no=@loop
insert into #Bought(Boughtdate,Boughtamount,R_NO)
select Date,Sum(Amount),@loop R_NO from Bought where date=(
select max(date) from bought B
where B.Date<@ProdDate)
group by Date
set @loop=@loop-1
end
select ProductionDate,ProductionAmount,Boughtdate,Boughtamount from #Bought B
join #Production p on B.R_NO=P.R_NO