现在我有TableB AS B
(Date, Store, Product, Qty)
('4/1/20', '1', 'A', '5'),
('4/9/20', '2', 'A', '5'),
('4/1/20', '2', 'A', '4'),
('4/1/20', '3', 'B', '3'),
('4/2/20', '3', 'B', '1'),
('4/2/20', '5', 'C', '2')
和表D AS D
(Product, Effective, Cost)
('A', '4/1/20', '100'),
('A', '4/8/20', '120'),
('B', '4/1/20', '100'),
('B', '4/8/20', '110'),
('C', '4/1/20', '100')
我想要 SUM(B.Qty * D.Cost) AS TotalCOst 但也需要基于生效日期。
ex IF 商店 1 产品 A 的日期为“4/1/20”,因此总成本为 5100 = 500 但如果商店 1 产品 A 的日期为“4/9/20”,则总成本为 5120 = 600
您能指导我吗?
这是我尝试过的,但结果现在仍然正确。
SELECT
B.Date,
D.Effective,
Datediff(DAY, B.Date, D.Effective) AS Datediff,
B.Store,
B.Product,
SUM(D.Cost) AS Cost,
SUM(D.Cost * B.Qty) AS TotalCost,
CASE WHEN Datediff(DAY, D.Effective, B.Date) >= 0 THEN SUM(D.Cost) ELSE 0 END AS Cost_Temp,
CASE WHEN Datediff(DAY, D.Effective, B.Date) >= 0 THEN SUM(D.Cost * B.Qty) ELSE 0 END AS TotalCost_Temp
FROM TableB AS B
INNER JOIN TableD AS D ON B.Product = D.Product
GROUP BY
B.Date,
B.Store,
B.Product,
D.Effective
ORDER BY B.Date
诀窍是找到有效的价格。这可以在 SQL Server 中使用
OUTER APPLY
来完成。我们想要做的就是选择表 D 中该日期有效的最新汇率。(我猜这是某种销售日期。)
我们通过简单的查询得到了
SELECT TOP 1 -- Because we only want the most recent
D.COST
FROM
TableD AS D
WHERE
D.EFFECTIVE <= B.DATE -- Only those prices that could be in effect
AND D.PRODUCT = B.PRODUCT -- Only the product of interest
AND D.STORE = B.STORE -- Only the store of interest
ORDER BY D.EFFECTIVE DESC -- To make sure the most recent is first
;
因此,在
OUTER APPLY
中将上述内容作为子选择,您将获得所需的行。我认为案例陈述不再需要。
SELECT
B.[DATE]
,D.EFFECTIVE
,DATEDIFF( DAY, B.[DATE], D.EFFECTIVE ) AS 'DATEDIFF'
,B.STORE
,B.PRODUCT
,SUM( D.COST ) AS 'COST'
,SUM( D.COST * B.QTY ) AS 'TOTAL_COST'
FROM
TableB B
OUTER APPLY ( SELECT TOP 1 *
FROM TableD D1
WHERE B.PRODUCT = D1.PRODUCT
AND B.[DATE] >= D1.EFFECTIVE
ORDER BY D1.EFFECTIVE DESC ) D
GROUP BY
B.[DATE],
B.STORE,
B.PRODUCT,
D.EFFECTIVE
ORDER BY
B.[DATE]
;
测试这一点的一个好方法是运行以下查询,该查询显示逐行比较。您可以查看表 A 中每行选择的生效日期以及使用的成本。
SELECT
B.[DATE]
,D.EFFECTIVE
,DATEDIFF( DAY, B.[DATE], D.EFFECTIVE ) AS 'DATEDIFF'
,B.STORE
,B.PRODUCT
,D.COST
,B.QTY
,D.COST * B.QTY AS 'TOTAL_COST'
FROM
TableB AS B
OUTER APPLY ( SELECT TOP 1 *
FROM TableD AS D1
WHERE B.PRODUCT = D1.PRODUCT
AND B.[DATE] >= D1.EFFECTIVE
ORDER BY D1.EFFECTIVE DESC ) D
ORDER BY
B.[DATE]
;
这是我从中得到的:
+------------+------------+----------+-------+---------+--------+-----+------------+
| DATE | EFFECTIVE | DATEDIFF | STORE | PRODUCT | COST | QTY | TOTAL_COST |
+------------+------------+----------+-------+---------+--------+-----+------------+
| 2020-04-01 | 2020-04-01 | 0 | 2 | A | 100.00 | 4 | 400.00 |
| 2020-04-01 | 2020-04-01 | 0 | 3 | B | 100.00 | 3 | 300.00 |
| 2020-04-01 | 2020-04-01 | 0 | 1 | A | 100.00 | 5 | 500.00 |
| 2020-04-02 | 2020-04-01 | -1 | 3 | B | 100.00 | 1 | 100.00 |
| 2020-04-02 | 2020-04-01 | -1 | 5 | C | 100.00 | 2 | 200.00 |
| 2020-04-09 | 2020-04-08 | -1 | 2 | A | 120.00 | 5 | 600.00 |
+------------+------------+----------+-------+---------+--------+-----+------------+