如果所有标准满足pl / sql,则返回值

时间:2018-05-08 17:03:03

标签: plsql

我有一张表例如

  

用户|城市

     

1 | A
  1 |乙
  1 | C
  2 | A
  2 | C
  3 | A
  3 | C
  4 | A
  5 |乙

我希望它只在用户位于城市A而C而不是A或C本身时才返回。即。

返回

  

用户|城市

     

1 | A
  1 | C
  2 | A
  2 | C
  3 | A
  3 | C

2 个答案:

答案 0 :(得分:0)

我必须认为这对于真实数据集来说是低效的,但这适用于您的示例数据。 ' TBL'只是源数据。真正的解决方案从内部选择开始,其中每行返回以及城市在集合中的usr值的计数' A' C'。然后,选择计数为2的usr和city,表示两者都匹配。无论如何,这是一个开始。

with tbl(usr, city) as (
  select 1, 'A' from dual union all
  select 1, 'B' from dual union all
  select 1, 'C' from dual union all
  select 2, 'A' from dual union all
  select 2, 'C' from dual union all
  select 3, 'A' from dual union all
  select 3, 'C' from dual union all
  select 4, 'A' from dual union all
  select 5, 'B' from dual
)
select usr, city
from ( 
  select usr, city, count(*)
  over (partition by usr) city_count
  from tbl
  where city in ('A', 'C')
)
where city_count = 2;

输出:

USR|CITY
1|A
1|C
2|A
2|C
3|A
3|C

答案 1 :(得分:0)

这是另一种方法,更高效,因为它没有使用COUNT函数,但是并不完全满足所需的输出格式,尽管我认为输出格式仍然可以接受,因为要求似乎是检索符合条件的USR:

WITH TBL(USR, CITY) AS (
  SELECT 1, 'A' FROM DUAL UNION ALL
  SELECT 1, 'B' FROM DUAL UNION ALL
  SELECT 1, 'C' FROM DUAL UNION ALL
  SELECT 2, 'A' FROM DUAL UNION ALL
  SELECT 2, 'C' FROM DUAL UNION ALL
  SELECT 3, 'A' FROM DUAL UNION ALL
  SELECT 3, 'C' FROM DUAL UNION ALL
  SELECT 4, 'A' FROM DUAL UNION ALL
  SELECT 5, 'B' FROM DUAL
)

SELECT USR_CITY_A.USR, USR_CITY_A.CITY, USR_CITY_B.CITY  
FROM (SELECT USR, CITY FROM TBL WHERE CITY = 'A') USR_CITY_A  
    ,(SELECT USR, CITY  FROM TBL WHERE CITY = 'C') USR_CITY_B  
WHERE USR_CITY_A.USR = USR_CITY_B.USR;   

输出:

USR | CITY A | CITY C

1 | A | C   
2 | A | C  
3 | A | C