MAX()WHERE - 错误

时间:2012-07-03 02:39:28

标签: php mysql

我有一个选择语句(工作

 Select * FROM 
    (SELECT id, type, color, product,  
    SUM(Quantity) AS TotalQuantity, 
    MAX(Date) AS LatestDate 
    FROM inventory 
    GROUP BY id, color, type) 
    AS alias 
    WHERE TotalQuantity > 0

我正在尝试向Max(日期)添加WHERE子句,但我没有运气:

我以为我只会将其更改为:MAX(Date) AS LatestDate WHERE stock = 1但这不起作用。

不工作:

 Select * FROM 
    (SELECT id, type, color, product,  
    SUM(Quantity) AS TotalQuantity, 
/* Problem Here */ MAX(Date) AS LatestDate WHERE stock = 1
    FROM inventory 
    GROUP BY id, color, type) 
    AS alias 
    WHERE TotalQuantity > 0

2 个答案:

答案 0 :(得分:2)

MAX(IF(stock = 1, Date, NULL)) AS LatestDate

如果没有这样的行,它会找到stock = 1null的最长日期

答案 1 :(得分:1)

使用Sub Select语句中的WHERE子句!

要获得答案,请使用此SQL:

Select * FROM 
    (SELECT id, type, color, product,  
    SUM(Quantity) AS TotalQuantity, 
    MAX(Date) AS LatestDate 
    FROM inventory 
    GROUP BY id, color, type
    WHERE TotalQuantity > 0) 
    AS alias

使用Sub Select语句中的WHERE子句!