我有一个交易库存数据库。它有销售和收据。我希望在销售时将库存销售与最后成本相匹配。我正在尝试编写SQL查询,但无法确定如何执行子查询或正确连接
数据看起来像这样:
STOCKCODE DATE TYPE QTY UNIT_VALUE TOTAL_VALUE
ABC123 01/Dec RECEIPT 10 100.00 1000.00
ABC123 02/Dec SALES -8 120.00 960.00
ABC123 03/Dec RECEIPT 10 110.00 1100.00
ABC123 04/Dec SALES -12 120.00 1440.00
所以目前的最后成本是110.00美元。 但我希望在12月02日售出8个单位(即100.00美元)时找到最后成本
答案 0 :(得分:0)
我认为使用apply运算符可以在这里工作:
select t.*, oa.last_value
from yourtable t
outer apply (
select top(1) unit_value as last_value
from yourtable y
where t.stockcode = y.stockcode
and y.type = 'RECEIPT'
and y.[date] < t.[date]
order by y.[date] DESC
) oa
我不确定[type]是否在这个逻辑中起作用,我怀疑它确实如此。
下面有一个查询usg coalesce()的小附加内容:请参阅SQL Fiddle Demo
CREATE TABLE yourtable
([STOCKCODE] varchar(6), [DATE] datetime, [TYPE] varchar(7), [QTY] int, [UNIT_VALUE] int, [TOTAL_VALUE] int)
;
INSERT INTO yourtable
([STOCKCODE], [DATE], [TYPE], [QTY], [UNIT_VALUE], [TOTAL_VALUE])
VALUES
('ABC123', '2001-12-01 00:00:00', 'RECEIPT', 10, 100.00, 1000.00),
('ABC123', '2001-12-02 00:00:00', 'SALES', -8, 120.00, 960.00),
('ABC123', '2001-12-03 00:00:00', 'RECEIPT', 10, 110.00, 1100.00),
('ABC123', '2001-12-04 00:00:00', 'SALES', -12, 120.00, 1440.00)
;
查询1 :
select t.*, coalesce(oa.last_value,unit_value) last_value
from yourtable t
outer apply (
select top(1) unit_value as last_value
from yourtable y
where t.stockcode = y.stockcode
and y.type = 'RECEIPT'
and y.[date] < t.[date]
order by y.[date] DESC
) oa
<强> Results 强>:
| STOCKCODE | DATE | TYPE | QTY | UNIT_VALUE | TOTAL_VALUE | last_value |
|-----------|----------------------|---------|-----|------------|-------------|------------|
| ABC123 | 2001-12-01T00:00:00Z | RECEIPT | 10 | 100 | 1000 | 100 |
| ABC123 | 2001-12-02T00:00:00Z | SALES | -8 | 120 | 960 | 100 |
| ABC123 | 2001-12-03T00:00:00Z | RECEIPT | 10 | 110 | 1100 | 100 |
| ABC123 | 2001-12-04T00:00:00Z | SALES | -12 | 120 | 1440 | 110 |