我的日历日期介于'2020-01-01'和'2020-01-03'之间。我如何在不使用联合的情况下将每个日期的总和数带到每个日期,我尝试了以下查询:
SELECT
Date,
Sum(ILE.Quantity)
FROM
Calender C
LEFT JOIN
[XYZ$Item Ledger Entry] ILE
ON
C.Date <= Cast(ILE.[Posting Date] as Date )
WHERE
Date BETWEEN '2020-01-01' AND '2020-01-03'
GROUP BY
Date;
我希望我的结果看起来像下面
Date Qty
01-01-2020 24550318.91
01-02-2020 24321291.58
01-03-2020 24526795.94
Select Date from Calendar C Where Date Between '2020-01-01'And '2020-01-03'
Select '2020-01-01'[Qty Till],Sum(ILE.Quantity)From[XYZ$Item Ledger Entry]ILE Where [Posting Date] <= '2020-01-01'
Select '2020-01-03'[Qty Till],Sum(ILE.Quantity) From[XYZ$Item Ledger Entry]ILE Where [Posting Date] <= '2020-01-02'
Select '2020-01-03'[Qty Till],Sum(ILE.Quantity) From[XYZ$Item Ledger Entry]ILE Where [Posting Date] <= '2020-01-03'
您的查询应该可以,但是我相信您的情况可能会相反。以下内容仅考虑前三天过去的条目:
C.Date <= Cast(ILE.[Posting Date] as Date)
如果要记录上一个>]这些日期,则需要对其进行切换:
Cast(ILE.[Posting Date] as Date) <= C.Date
如果要加快查询速度,请在
[Posting Date]
列上创建索引:
CREATE NONCLUSTERED INDEX NCI_LedgerEntry_PostingDate ON [XYZ$Item Ledger Entry] ([Posting Date])
然后避免在比较中强制使用最新的值(尽管引擎可能仍使用索引,但不确定):
ILE.[Posting Date] < DATEADD(DAY, 1, C.Date)