[英]Query to get distinct values only on group of columns
If I have the following table: 如果我有下表:
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
The query should return 查询应返回
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
The following rules apply: 适用以下规则:
- 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
The DB platform is DB2, but any SQL is good, at this point, as long as it's pure SQL. DB平台是DB2,但是,只要纯SQL,此时任何SQL都是好的。
I do not manage to get the DISTINCT rule to apply to only (NAME, CAR), on the whole row, and if more than one row exists with the same (NAME, CAR), get the row with highest NUMBER. 我没有设法使DISTINCT规则仅适用于整行(NAME,CAR),并且如果同一行(NAME,CAR)存在多个行,则获得NUMBER最高的行。
In pure, unadulterated ansi-92 SQL: 在纯净的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
This should do the trick 这应该可以解决问题
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
I think a group by can help. 我认为一个小组可以提供帮助。
select id, max(number), event, name, car from foo group by name, car
This works in MySQL, but not in DB. 这适用于MySQL,但不适用于DB。 Apparently MySQL is much more straight-forward.
显然,MySQL更简单明了。
Try this SELECT statement 试试这个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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.