表 PURCHASE(PDate, ItemName, PQty, Rate)
PDate | ItemName | PQty | Rate
============================================
01-04-2015 | Mobile Phone | 06 | 05,000
01-04-2015 | Laptop | 07 | 30,000
03-04-2015 | Mobile Phone | 03 | 06,000
04-04-2015 | Mobile Phone | 08 | 07,000
04-04-2015 | Laptop | 03 | 40,000
05-04-2015 | Mobile Phone | 05 | 04,000
表 SALES(SDate, ItemName, SQty)
SDate | ItemName | SQty
=================================
02-04-2015 | Mobile Phone | 02
03-04-2015 | Laptop | 03
03-04-2015 | Mobile Phone | 05
04-04-2015 | Mobile Phone | 07
04-04-2015 | Laptop | 03
06-04-2015 | Laptop | 02
SQL
表 EXPECTED SELECT QUERY RESULT (Date, ItemName, Qty, Rate, ProductValue)
PDate | ItemName | PQty | Rate | ProductValue
===========================================================
01-04-2015 | Mobile Phone | 00 | 05,000 | 0.00
01-04-2015 | Laptop | 00 | 30,000 | 0.00
03-04-2015 | Mobile Phone | 00 | 06,000 | 0.00
04-04-2015 | Mobile Phone | 03 | 07,000 | 21,000.00
04-04-2015 | Laptop | 02 | 40,000 | 80,000.00
05-04-2015 | Mobile Phone | 05 | 04,000 | 20,000.00
如何解决这个问题?
答案 0 :(得分:1)
SELECT PDate, ItemName, MPQty, PQty, ISNULL(SQty,0) AS SQty,
ISNULL((CASE WHEN SQTY>=PQty THEN 0 WHEN (SQty+MPQty)>PQty THEN PQty-SQty ELSE MPQty END),0) AS Qty, Rate,
(ISNULL((CASE WHEN SQTY>=PQty THEN 0 WHEN (SQty+MPQty)>PQty THEN PQty-SQty ELSE MPQty END),0)*Rate) AS PValue FROM
(SELECT P.PDate AS PDate, P.ItemName AS ItemName, P.PQty AS MPQty,
(SELECT SUM(P1.PQty) FROM PURCHASE P1 WHERE P1.ItemName=P.ItemName AND P1.PDate<=P.PDate) AS PQty,
(SELECT SUM(S1.SQty) FROM SALES S1 WHERE S1.ItemName=P.ItemName) AS SQty,
P.Rate AS Rate FROM PURCHASE P)X ORDER BY Pdate