如果我有下表:
Table name: FOO
ID | NUMBER | EVENT | NAME | CAR
1 | 12 | OFFER | Adam | VW
2 | 13 | ORDER | Adam | VW
3 | 11 | OFFER | Adam | BMW
4 | 12 | OFFER | Adam | BMW
5 | 3 | OFFER | Adam | BMW
6 | 1 | ORDER | Mark | Mercedes
7 | 1 | ORDER | Mark | BMW
查询应该返回
Result name: FOO
ID | NUMBER | EVENT | NAME | CAR
2 | 13 | ORDER | Adam | VW
4 | 12 | OFFER | Adam | BMW
6 | 1 | ORDER | Mark | Mercedes
7 | 1 | ORDER | Mark | BMW
以下规则适用:
- Get the records which have DISTINCT NAME AND CAR
- If more than one record with the same NAME AND CAR exists, get the one with MAX NUMBER
- ID, NUMBER, EVENT should not count towards the DISTINCT row rule
数据库平台是DB2,但只要它是纯SQL,任何SQL都是好的。
我无法在整行上将DISTINCT规则仅应用于(NAME,CAR),如果存在多个相同的行(NAME,CAR),则获取NUMBER最高的行。
答案 0 :(得分:2)
纯粹的,纯粹的ansi-92 SQL:
select t1.*
from Foo t1
inner join
(
select Name, Car, max(number) as maxNo
from Foo
group by Name, Car
) x2
on t1.Name = x2.Name
and t1.Car = x2.car
and t1.Number = x2.maxNo
答案 1 :(得分:2)
这应该可以解决问题
with temp as (
select id, number, event, name, car,
rownumber() over (partition by name, car order by number desc) as rownum
from foo
)
select id, number, event, name, car from temp
where rownum = 1
答案 2 :(得分:0)
我认为一个小组可以提供帮助。
select id, max(number), event, name, car from foo group by name, car
这适用于MySQL,但不适用于DB。显然,MySQL更直接。
答案 3 :(得分:0)
尝试此SELECT语句
SELECT FOO.ID, F.Number, Foo.Event, f.Name, f.Car
FROM FOO INNER JOIN
(
SELECT MAX(Number) AS Number, Name, Car
FROM FOO
GROUP BY Name, Car
) F ON FOO.Number = F.Number AND FOO.Name = F.Name AND Foo.Car = F.Car
ORDER BY FOO.ID