我希望通过“分组依据”获得结果,但不是靠运气。我可以看到其他选项,但寻找最佳性能查询。
预先感谢!
CREATE TABLE #Invoice (InvoiceId int, InvoiceDate datetime, NetAmount
decimal(18,2))
CREATE TABLE #Payment (PaymentId int, InvoiceId int, PaidAmount
decimal(18,2))
INSERT INTO #Invoice VALUES (101, '20180212', 5000)
INSERT INTO #Invoice VALUES (102, '20180112', 600)
INSERT INTO #Invoice VALUES (103, '20181211', 1800)
INSERT INTO #Invoice VALUES (104, '20180101', 1000)
INSERT INTO #Invoice VALUES (105, '20180212', 7000)
INSERT INTO #Payment VALUES (101,103,1800)
INSERT INTO #Payment VALUES (102,102,500)
INSERT INTO #Payment VALUES (103,101,2000)
INSERT INTO #Payment VALUES (103,101,3000)
创建此查询:
SELECT
INV.InvoiceDate,
SUM(Inv.NetAmount) as NetAmount,
SUM(ISNULL(PY.PaidAmount,0)) As PaidAmount
From #Invoice INV
LEFT JOIN #Payment PY
ON PY.InvoiceId = INV.InvoiceId
GROUP BY
INV.InvoiceDate
获取结果:
InvoiceDate NetAmount PaidAmount
2018-01-01 1000.00 0.00
2018-01-12 600.00 500.00
2018-02-12 17000.00 5000.00 ****问题:净值应该是12000而不是17000
2018-12-11 1800.00 1800.00
预期结果:
InvoiceDate NetAmount PaidAmount
2018-01-01 1000.00 0.00
2018-01-12 600.00 500.00
2018-02-12 5000.00 5000.00
2018-12-11 1800.00 1800.00
答案 0 :(得分:2)
假设 ,这是OP提供的预期结果错误。它们在5000
上具有NetAmount
的值20180212
,但是该日期有2张发票,分别具有值5000
和7000
,使得{{1 }}。如果12000
是正确的,我们需要详细说明为什么不包括发票5000
(105
)的值。
无论如何,假设预期结果是错误的,那么我相信您正在寻找以下结果:
7000