我必须将表ProdBiscuit作为tb和StockData作为sd,我必须得到StockData(quantite)中数量的总和,条件为if(sd.status> 0和sd.prodid = tb.id AND sd .matcuisine = 3)
这是我的SQL查询
SELECT tb.id, tb.nom, tb.proddate, tb.qty, tb.stockrecno
FROM ProdBiscuit AS tb
JOIN
(SELECT id, prodid, matcuisine, status, SUM(quantite) AS rq FROM StockData) AS sd
ON (tb.id = sd.prodid AND sd.status > 0 AND sd.matcuisine = 3) LIMIT 25 OFFSET @Myid
这根本不给我任何行?
ProdBiscuit中只有3行,Stockdata中只有11行,StockData中只有2行符合条件。
如图所示,只有两行给出了条件。
我的查询有什么问题?
PS:图像上的绿线显示我查询中的条件。
答案 0 :(得分:2)
请检查一下。如果您没有得到想要的结果,请转到SQLFiddle.com并使用数据创建示例表,以便更容易找出您想要的结果。
SELECT tb.id, tb.nom, tb.proddate, tb.qty, tb.stockrecno, SUM(sd.quanite)
FROM ProdBiscuit AS tb
JOIN StockData AS sd
ON tb.id = sd.prodid
WHERE sd.status > 0 AND sd.matcuisine = 3
GROUP BY tb.id, tb.nom, tb.proddate, tb.qty, tb.stockrecno
答案 1 :(得分:0)
SELECT tb.id, tb.nom, tb.proddate, tb.qty, tb.stockrecno, SUM(quantite) As rq
FROM ProdBiscuit AS tb
JOIN StockData AS sd ON (tb.id = sd.prodid AND sd.status > 0 AND sd.matcuisine = 3)
OR (tb.id = sd.prodid AND sd.status = 0 AND sd.matcuisine = 3)
GROUP BY tb.id, tb.nom, tb.proddate, tb.qty, tb.stockrecno
这个查询给了我这个
ID NOM QTY RQ
1 Biscuit Chocolat 100 100
2 Biscuit Moutarde 120 226
3 Biscuit Pain Epice 100 100
AND Happy End在@AgRizzo的帮助下我做了一些修改并添加了准确的显示:
SELECT tb.id, tb.nom, tb.proddate, tb.qty, tb.stockrecno,
SUM(IF((status>0 AND tb.id=sd.prodid),quantite,0)) As rq FROM ProdBiscuit AS tb
JOIN StockData AS sd ON (tb.id = sd.prodid AND sd.status > 0 AND sd.matcuisine = 3)
OR (tb.id = sd.prodid AND sd.status = 0 AND sd.matcuisine = 3)
GROUP BY tb.id, tb.nom, tb.proddate, tb.qty, tb.stockrecno
ID NOM QTY RQ
1 Biscuit Chocolat 100 100
2 Biscuit Moutarde 120 14
3 Biscuit Pain Epice 100 100
Code for displaying the "rq" is:
QtyLst.Items.Add((Convert.ToInt16(reader["qty"])- Convert.ToInt16(reader["rq"])).ToString());