以下列方式的数据表;
Firm | PartID | StockCount | Date | Type
-----------------------------------------------------------
1 | 71 | 5 | 2014-02-01 | Incoming Invoice
1 | 71 | -1 | 2014-02-09 | Send Invoice
1 | 71 | 10 | 2014-02-13 | Stocktaking ( !!! Of the Depot. )
1 | 71 | -1 | 2014-02-21 | Send Invoice
1 | 71 | 5 | 2014-02-28 | Incoming Invoice
这张表实际上是一张股票,是一张虚构的动作表描写。此表中的商店,购买和销售发票中的计数包括。这样,从仓库和仓库进入仓库将收集在实际计算的表数量中。从进行人口普查的那一刻起,股票价值应该按照规定的金额计算。问题即将来临。
如何获得以下结果?
Firm | PartID | StockCount | Date | Type
-------------------------------------------------------
1 | 71 | 14 | NULL | NULL
答案 0 :(得分:0)
如果我正确阅读:
SELECT firm, partid, count(stockCount) as stock_total
FROM yourtable
WHERE firm = 1
AND partid = 71
如果要选择多个部分,则需要分组,例如:
SELECT firm, partid, count(stockCount) as stock_total
FROM yourtable
WHERE firm = 1
GROUP BY partid
答案 1 :(得分:0)
试试这个
SELECT Firm,
PartID,
Count(StockCount),
Date AS NULL,
TYPE AS NULL
FROM TABLE
GROUP BY Firm,
PartID
答案 2 :(得分:0)
您对此问题的解释尚不清楚,但我认为这是您想要的。
SELECT Firm, PartID, SUM(StockCount) as StockCount, NULL as Date, NULL as Type
FROM tbl T1
WHERE Date >= (SELECT Date FROM tbl T2
WHERE T2.Type = Stocktaking
AND T1.Firm =T2.Firm
AND T1.PartId = T2.PartId
)
GROUP BY Firm, PartID
答案 3 :(得分:0)
你似乎想要"库存"之后的股票总和,我怀疑它通常被称为"做库存"用英语。
select Firm, PartId, sum(StockCount) as StockCount, NULL as Date, NULL as Type
from table t
where Date >= (select max(Date)
from table t2
where t2.Firm = t.Firm and
t2.partid = t.partid and
t2.type = 'Stocktaking'
)
group by Firm, Partid;
如果可能没有Stocktaking记录,那么请采用left join
方法:
select Firm, PartId, sum(StockCount) as StockCount, NULL as Date, NULL as Type
from table t left join
(select Firm, PartId, max(Date) as maxDate
from table t
where t2.type = 'Stocktaking'
group by Firm, PartId
) as tfp
on t.Firm = tfp.Firm and t.PartId = tfp.PartId and t.Date >= tfp.MaxDate
group by t.Firm, t.PartId;