MySQL:如何通过某些数据限制SUM查询?

时间:2012-10-23 03:03:19

标签: php mysql sum

我有这样的查询:

SELECT DATE(Inspection_datetime) AS Date,Line,TRIM(Model) AS Model, Lot_no,
    COUNT(Serial_number) AS Qty
FROM inspection_report 
WHERE Line LIKE 'FA 06' AND MONTH(Inspection_datetime) = MONTH(CURRENT_DATE)
GROUP BY DATE(Inspection_datetime), TRIM(Model),Line,Lot_no

结果:

   Date     Line    Model      Lot_no  Qty                 
2012-10-19  FA 06   KD-X30EED   012A    1
2012-10-21  FA 06   KD-R446UD   024A    20
2012-10-21  FA 06   KD-R446UD   026A    25
2012-10-22  FA 06   KD-R430JD   052A    20
2012-10-22  FA 06   KD-R446UD   026A    15
2012-10-22  FA 06   KD-R540JD   025A    30
2012-10-23  FA 06   KD-R540JD   025A    10
2012-10-23  FA 06   KD-R540JD   027A    2

如果我希望SUM数据直到这个数据怎么办:

2012-10-22  FA 06   KD-R446UD   026A    15

我试过这个:

SELECT SUM(X.Qty) AS QTY
FROM (
    SELECT DATE(Inspection_datetime) AS Date,Line,TRIM(Model) AS Model, Lot_no,     COUNT(Serial_number) AS Qty
    FROM inspection_report 
    WHERE Line LIKE 'FA 06' AND MONTH(Inspection_datetime) = MONTH(CURRENT_DATE)
    GROUP BY DATE(Inspection_datetime), TRIM(Model),Line,Lot_no) AS X
WHERE ?????????? 

我想要结果像:

|Qty |
+----+       
|81  |

修改

如果我选择数据停止在2012-10-21 FA 06 KD-R446UD 026A 25计数 我会得到Qty =46 如果这个问题与MySQL Query无关,那怎么办PHP?

1 个答案:

答案 0 :(得分:0)

您可以使用正在运行的总变量,如下所示:

SET @total = 0;
SELECT
    (@total := @total + X.qty) AS qty,
    X.Model
FROM (
    SELECT
        DATE(Inspection_datetime) AS Date,
        Line,
        TRIM(Model) AS Model,
        Lot_no,
        COUNT(Serial_number) AS Qty
    FROM inspection_report
    WHERE Line LIKE 'FA 06'
      AND MONTH(Inspection_datetime) = MONTH(CURRENT_DATE)
    GROUP BY 1, 3, 2, 4
) AS X
WHERE @total <= 81