假设我有一个名为'CarMaker'的表列,我可能有本田,丰田,福特等。在第二栏,我有'CarYear',如1999,1958,2006等。我如何写一个查询来获得丰田,其中年份是所有丰田汽车中最高的,但它不一定是列中所有汽车的MAX值。
答案 0 :(得分:2)
SELECT *
FROM cars
WHERE ( CarModel, CarYear ) = (
SELECT CarModel, max( CarYear )
FROM cars
WHERE CarModel = 'Toyota'
GROUP BY CarModel
)
答案 1 :(得分:0)
以下是解决此问题的一般方法:
SELECT t1.*
FROM yourTable t1
INNER JOIN
(
SELECT CarMaker, MAX(year) AS max_year
FROM yourTable
GROUP BY CarMaker
) t2
ON t1.CarMaker = t2.CarMaker AND t1.year = t2.max_year;
这将为所有汽车制造商带来最新型号。如果您想限制特定的汽车制造商,那么您可以在上述查询的末尾添加WHERE
子句:
WHERE t1.CarMaker = 'Toyota'
请注意,这将返回最近一年恰好出现的所有丰田车型,因此如果不止一个型号适合此类别,那么所有车型都将退回。如果您不想要这种行为,那么您应该给出关于应该返回哪些最新模型的逻辑。
答案 2 :(得分:0)
这应该这样做:
SELECT * FROM
(
SELECT CarMaker, MAX(CarYear) as mxYear
FROM table
GROUP BY CarMaker
) WHERE CarMaker = 'Toyota'
答案 3 :(得分:0)
您可以使用窗口功能:
select *
from (
select carmaker,
caryear,
max(caryear) over (partition by carmaker) as max_year
from the_table
) t
where caryear = max_year
and carmaker = 'Toyota';
答案 4 :(得分:0)
您还可以将subquery
与相关方法一起使用:
select c.*
from cars c
where CarYear = (select max(c1.CarYear)
from cars c1
where c1.CarModel = c.CarModel
);
但是,如果是这样,这可能会给你重复记录,那么你可以改为PK
:
select c.*
from cars c
where pk = (select pk -- top (1) if your has no support of limit clause
from cars c1
where c1.CarModel = c.CarModel
order by c1.CarYear desc
limit 1 -- DBMS specific some other uses TOP clause instead
);