[英]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. 我正在使用jpa,需要弄清楚我只需要2张桌子的奇怪过滤器。
Description: 描述:
Find the rows with a distinct rte, cd combination with the smallest id (this would be row 1, 4, and 6). 查找具有唯一ID最小的rte,cd组合的行(这将是第1、4和6行)。 Now join these rows with Table 2 (fkey-pkey) in order to filter on the country.
现在,将这些行与表2(fkey-pkey)结合在一起,以便对国家/地区进行过滤。 If a match, return all the rows in table 1 with that distinct rte, cd combination.
如果匹配,则以该不同的rte,cd组合返回表1中的所有行。
sqlfiddle: http://sqlfiddle.com/#!9/bc932/7 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.
获取每个rte / cd中具有最低ID的行的fkey。 Then, join to country.
然后,加入乡村。 Then join back to get the rest of the rows from table 1.
然后重新加入以获取表1中的其余行。
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. 如果JPA甚至不支持
NOT EXISTS
,请尝试将查询创建为数据库视图并将该视图提供给JPA。
Also, the WITH/DENSE_RANK version would run faster, so that's the one to use if you go the view-route. 另外,WITH / DENSE_RANK版本将运行得更快,因此如果您使用视图路径,则可以使用该版本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.