[英]SQL 2 table odd filter required (Oracle)
我正在使用jpa,需要弄清楚我只需要2张桌子的奇怪过滤器。
描述:
查找具有唯一ID最小的rte,cd组合的行(这将是第1、4和6行)。 现在,将这些行与表2(fkey-pkey)结合在一起,以便对国家/地区进行过滤。 如果匹配,则以该不同的rte,cd组合返回表1中的所有行。
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
如果我过滤美国,结果将是:
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'
语法没有检查错别字,但是这个想法应该可行。 获取每个rte / cd中具有最低ID的行的fkey。 然后,加入乡村。 然后重新加入以获取表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'
如果JPA甚至不支持NOT EXISTS
,请尝试将查询创建为数据库视图并将该视图提供给JPA。
另外,WITH / DENSE_RANK版本将运行得更快,因此如果您使用视图路径,则可以使用该版本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.