我有一个选择语句(工作)
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
答案 0 :(得分:2)
MAX(IF(stock = 1, Date, NULL)) AS LatestDate
如果没有这样的行,它会找到stock = 1
或null
的最长日期
答案 1 :(得分:1)
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
子句!