使用SQL变量时的排序问题

时间:2017-10-18 07:50:44

标签: mysql sql

我运行此查询:

SELECT stockcarddetail.id, stockcarddetail.date, stockcarddetail.quantity, stockcarddetail.pricePerItem
  FROM Stockcard
  LEFT JOIN staff
         ON staff.branchId = stockcard.branchId
  LEFT JOIN stockcarddetail
         ON stockcarddetail.stockcardId = stockcard.id
 WHERE staff.username = 'jemmy.h'
   AND stockcarddetail.quantity > 0
   AND stockcard.productId = '98924a5f-6afb-11e7-8dd4-2c56dcbcb038'
 ORDER BY date ASC

并获得以下结果:

id | date       | quantity| pricePerItem
50 | 2017-10-15 | 10.00   | 10000.00
1  | 2017-10-18 | 20.00   | 10000.00

然后,我需要根据上面的顺序计算累计数量,所以我运行这个查询:

SELECT a.*, @tot:=@tot + a.quantity FROM
(SELECT @tot:= 0)b
JOIN
(SELECT stockcarddetail.id, stockcarddetail.date, stockcarddetail.quantity, stockcarddetail.pricePerItem
FROM Stockcard
LEFT JOIN staff
       ON staff.branchId = stockcard.branchId
LEFT JOIN stockcarddetail
       ON stockcarddetail.stockcardId = stockcard.id
WHERE staff.username = 'jemmy.h'
  AND stockcarddetail.quantity > 0
  AND stockcard.productId = '98924a5f-6afb-11e7-8dd4-2c56dcbcb038'
ORDER BY date ASC) a

然后我得到了这个结果:

id | date       | quantity| pricePerItem | @tot
1  | 2017-10-18 | 20.00   | 10000.00     | 20
50 | 2017-10-15 | 10.00   | 10000.00     | 30

然而,我想要的结果是这样的:

id | date       | quantity| pricePerItem | @tot
50 | 2017-10-15 | 10.00   | 10000.00     | 10
1  | 2017-10-18 | 20.00   | 10000.00     | 30

如何获得预期结果?

修改

问题的简化版本可以在这里找到:http://sqlfiddle.com/#!9/f6ad91/3

2 个答案:

答案 0 :(得分:1)

根据我的理解,您需要每个条目的累计总数。

我建议放弃变量并依赖子查询:

SELECT  
scd.id,  
scd.date,  
scd.quantity,  
scd.pricePerItem, 
(SELECT SUM(scd1.quantity) FROM StockcardDetail AS scd1 WHERE scd1.stockcardId = scd.stockcardId AND scd1.date <= scd.date) AS total 
FROM Stockcard 
LEFT JOIN staff ON staff.branchId = stockcard.branchId 
LEFT JOIN stockcarddetail AS scd ON scd.stockcardId = stockcard.id

WHERE staff.username = 'jemmy.h'  
AND scd.quantity > 0  
AND stockcard.productId = '98924a5f-6afb-11e7-8dd4-2c56dcbcb038' 
ORDER BY scd.date ASC

这背后的想法是让它为每个条目选择之前(包括当前条目)的所有条目的总和。

答案 1 :(得分:1)

根据我的理解,您应该从查询中获得预期的输出。但是,您没有获得预期的输出,那么其他可能的解决方案是(没有JOIN

SET @tot:= 0;

SELECT 
stockcarddetail.id, 
stockcarddetail.date, 
stockcarddetail.quantity, 
stockcarddetail.pricePerItem, 
@tot:=@tot + stockcarddetail.quantity as Total
FROM Stockcard
LEFT JOIN staff ON staff.branchId = stockcard.branchId
LEFT JOIN stockcarddetail ON stockcarddetail.stockcardId = stockcard.id
WHERE staff.username = 'jemmy.h' AND stockcarddetail.quantity > 0 AND stockcard.productId = '98924a5f-6afb-11e7-8dd4-2c56dcbcb038'
ORDER BY date ASC