我有这样的事情:
SELECT foo1, foo2, foo3, MAX(foo4) AS max FROM table WHERE foo5 = bar;
问题是,除了将WHERE foo5 = bar子句应用于整个查询之外,我还想为foo4指定一个条件。我不仅希望整个表中的foo4的最大值,而是另一个字段等于特定内容时foo4的最大值。就像这样。
SELECT foo1, foo2, foo3, MAX(foo4 WHERE field=otherthing) AS max FROM table WHERE foo5 = bar;
我该怎么做?
编辑:这是一些更详细的信息。这是我目前的查询:
SELECT Car_Type, Car_Imm, MIN(Use_Kilom) AS Init_Kilom,
MAX(Use_Kilom) AS Final_Kilom, MAX(Use_Kilom)
- MIN(Use_Kilom) AS Distance_Kilom, null, null,
SUM(Use_Amount) AS Amount_Total,
SUM(Use_Liter) / 20 AS Liter_Total, null, null
FROM fueluse, car
WHERE Use_Car = Car_Code AND
(Use_Date BETWEEN '$datefrom' AND '$dateto')
在这种情况下,MAX(Use_Kilom)和MIN(Use_Kilom)都从整个表中获取绝对最大值和最小值。我只是希望他们获得每个Use_Car值的最大值。
我尝试分别用以下内容替换它们:
(SELECT MIN(Use_Kilom) FROM fueluse, car WHERE Use_Car = Car_Code) AS Init_Kilom
(SELECT MAX(Use_Kilom) FROM fueluse, car WHERE Use_Car = Car_Code) AS Final_Kilom
但他们仍然在整个fueluse表的Use_Kilom字段中给出绝对最小值和最大值,而不仅仅是每个Use_Car的Use_Kilom的最大值和最小值。请注意,Use_Car和Car_Code被链接为外键。
答案 0 :(得分:1)
我希望看到group by子句然后使用聚合函数(min,max,sum等)。在这种情况下,可能由Car_Type,Car_Imm组。隐含连接也应该更改为显式连接。
SELECT Car_Type, Car_Imm, MIN(Use_Kilom) AS Init_Kilom,
MAX(Use_Kilom) AS Final_Kilom, MAX(Use_Kilom)
- MIN(Use_Kilom) AS Distance_Kilom, null, null,
SUM(Use_Amount) AS Amount_Total,
SUM(Use_Liter) / 20 AS Liter_Total, null, null
FROM fueluse
join car on Use_Car = Car_Code AND
where (Use_Date BETWEEN '$datefrom' AND '$dateto')
group by Car_Type, Car_Imm
如果您使用他们所属的表名(或他们的别名)限定您的字段名,这将使事情更清楚