MySQL SUBTRACT与SUM查询一个单列相同的表

时间:2013-07-11 23:48:14

标签: java mysql

Transactions_Table:

+---------+--------+-------------+--------------+-----+
| DocType | SFCode | Productname | WarrantyCode | QTY |
+---------+--------+-------------+--------------+-----+
|   FP    | 12     | Item        |    1111-01   | 100 | -100
|   FP    | 12     | Item        |    2222-22   | 200 | 
|   FP    | 12     | Item        |    3333-33   | 350 | -350

|   LP    | 12     | Item        |    4444-44   | 10  |
|   LP    | 12     | Item        |    5555-55   | 20  |
|   LP    | 12     | Item        |    6666-66   | 35  | -35

|   CAS   | 12     | Item        |    1111-01   | 50  | -(50 Left, show)
|   CRS   | 12     | Item        |    3333-33   | 120 | -(230 Left, show)
|   CRS   | 12     | Item        |    6666-66   | 35  | -(0 Left, no show)

|   FPR   | 12     | Item        |    1111-01   | 10  | -(40 Left, show)
|   LPR   | 12     | Item        |    5555-55   | 20  | -(0 Left, no show)
|   CSR   | 12     | Item        |    1111-01   | 5   | -(50+5 Left, show)
|   CRR   | 12     | Item        |    6666-66   | 5   | -(Got back 5, show)
+---------+--------+-------------+--------------+-----|

KEY:

FP: Foreign Purchase
LP: Local Purchase

CAS: Cash Sale
CRS: Credit Sale

FPR: Foreign Purchase Return
LPR: Local Purchase Return

CSR: Cash Sale Return
CRR: Credit Sale Return

现在有许多产品,但目前只关注单个SFCode“12”。

QTY是商店中的Physical Stock PRESENT,DocType是交易。

我需要对这个表做两件事。

  1. 获取当前股票(FP + LP + CSR + CRR) - (FPR + LPR + CAS + CRS)注意:可能没有特定DocType的交易

  2. 获取特定保修代码尚未售罄的产品的保修代码。在表格的最后一列(未命名)中从顶部到底部,你会得到这个想法。

  3. 请建议可帮助我实现此结果的Java-MySql语句。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

为#1尝试类似的事情:

SELECT SFCode, SUM(FP+LP+CSR+CRR-FPR-LPR-CAS-CRS) AS Total FROM
(SELECT SFCode,
SUM(IF(DocType = "FP", QTY, 0)) AS FP,
>>please fill out all the columns<<    
FROM Transactions_Table
WHERE SFCode = "12"
GROUP BY DocType);

这是我在#2的镜头:(假设SFCode不是整数)

SELECT a.SFCode, a.WarrantyCode, (a.QTY-b.QTY) AS Stock FROM
(SELECT SFCode, WarrantyCode, QTY
FROM Transactions_Table
WHERE SFCode = "12"
AND DocType IN ('FP','LP','CSR','CRR')
GROUP BY WarrantyCode) AS a 
LEFT JOIN
(SELECT SFCode, WarrantyCode, QTY
FROM Transactions_Table
WHERE SFCode = "12"
AND DocType IN ('FPR','LPR','CAS','CRS')
GROUP BY WarrantyCode) AS b
ON a.SFCode = b.SFCode AND a.WarrantyCode = b.WarrantyCode;

现在不能自己测试这个,但至少应该给你一个想法。