我有 2 張桌子ProductLog和Product
產品日志
ProductID TransDate RegNo
--------------------------------
15 2022-03-05 4
15 2022-03-08 1
15 2022-03-10 3
產品
Date ProductID
-----------------------
2022-03-01 15
2022-03-02 15
2022-03-03 15
2022-03-04 15
2022-03-05 15
2022-03-06 15
2022-03-07 15
2022-03-08 15
2022-03-09 15
2022-03-10 15
2022-03-11 15
2022-03-12 15
選擇陳述句的RegNo值為ProductLog.RegNo,即 Product.Date <= ProductLog.TransDate
我想得到如下 預期輸出的結果
Date ProductID RegNo
-------------------------------
2022-03-01 15 4
2022-03-02 15 4
2022-03-03 15 4
2022-03-04 15 4
2022-03-05 15 4
2022-03-06 15 1
2022-03-07 15 1
2022-03-08 15 1
2022-03-09 15 3
2022-03-10 15 3
2022-03-11 15 0
2022-03-12 15 0
我嘗試按 ASC 對日期進行排序,在 rank = 1 的情況下,它將全部設定為最低日期值。(我知道這不是一個正確的方法。)
解決這個問題的正確方法是什么?
uj5u.com熱心網友回復:
用于APPLY查找RegNo
select p.Date, p.ProductID, RegNo = coalesce(l.RegNo, 0)
from Product p
outer apply
(
select top 1 l.RegNo
from ProductLog l
where l.ProductID = p.ProductID
and l.TransDate >= p.[Date]
order by l.TransDate
) l
uj5u.com熱心網友回復:
使用 join 如下:
select
b.Date,
b.ProductID,
iif(RegNo is null, 0, RegNo)
from
Product b
full join ProductLog a on a.ProductID = b.ProductID
and b.Date <= a.TransDate
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/443784.html
