简体   繁体   中英

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.

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.

In pure, unadulterated 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. Apparently MySQL is much more straight-forward.

Try this SELECT statement

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM