简体   繁体   中英

SQL 2 table odd filter required (Oracle)

I'm using jpa and need to figure out this oddball filter i need with just 2 tables.

Description:

Find the rows with a distinct rte, cd combination with the smallest id (this would be row 1, 4, and 6). Now join these rows with Table 2 (fkey-pkey) in order to filter on the country. If a match, return all the rows in table 1 with that distinct rte, cd combination.

sqlfiddle: http://sqlfiddle.com/#!9/bc932/7

        Table 1

id       rte      cd     fkey
---      ----     ---    ----
1        A         E      21
2        A         E      24
3        A         E      24
4        B         W      24
5        B         W      21
6        C         E      21
7        C         E      30


        Table 2

pkey    country
----    -------
 21       US
 24       MX
 30       CA

If I filter on US, the result would be:

id       rte      cd     fkey
---      ----     ---    ----
1        A         E      21
2        A         E      24
3        A         E      24
6        C         E      21
7        C         E      30
WITH a AS (SELECT rte, cd, max(fkey) keep (dense_rank first order by id asc) first_fkey
FROM   table_1
GROUP BY rte, cd )
SELECT 
FROM a INNER JOIN table_2 ON table_2.pkey = a.first_fkey
INNER JOIN table_1 on table_1.rte = a.rte and table_1.cd = a.cd
WHERE table_2.country = 'US'

Syntax not checked for typos, but the idea should work. Get the fkey of the row in each rte/cd having the lowest ID. Then, join to country. Then join back to get the rest of the rows from table 1.

Alternate version - no WITH or DENSE_RANK

SELECT t1b.id, t1b.rte, t1b.cd, t1b.fkey
FROM table1 t1a,
     table2 t2,
     table1 t1b
WHERE t2.pkey = t1a.fkey
AND   t1b.rte = t1a.rte
and   t1b.cd = t1a.cd
and not exists ( SELECT 'x' FROM table1 t1c WHERE t1c.rte = t1a.rte and t1c.cd = t1a.cd and t1c.id < t1a.id )
and t2.country = 'US'

If JPA doesn't even support NOT EXISTS , try to create the query as a database view and give the view to JPA.

Also, the WITH/DENSE_RANK version would run faster, so that's the one to use if you go the view-route.

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