我在以下方面给予您帮助:
我有一张这样的桌子:
Table_Values
ID | Value | Date
1 | ASD | 01-Jan-2019
2 | ZXC | 10-Jan-2019
3 | ASD | 01-Jan-2019
4 | QWE | 05-Jan-2019
5 | RTY | 15-Jan-2019
6 | QWE | 29-Jan-2019
我需要获取重复的值并具有不同的日期,例如,值“ QWE”被重复并且具有不同的日期:
ID | Value | Date
4 | QWE | 05-Jan-2019
6 | QWE | 29-Jan-2019
答案 0 :(得分:0)
具有EXISTS:
select * from Table_Values t
where exists (
select 1 from Table_Values
where value = t.value and date <> t.date
)
答案 1 :(得分:0)
使用加入:
select
t1.*
from
Table_Values t1
join
Table_Values t2
on t1.Value = t2.Value
and t1.Date <> t2.Date
但是,“现有”方法更好。
答案 2 :(得分:0)
您希望每个值中有多个日期的所有行。您可以为此使用COUNT OVER
。
一种方法(自Oracle 12c起已启用):
select id, value, date
from mytable
order by case when count(distinct date) over (partition by value) > 1 then 1 else 2 end
fetch first row with ties
但是,如果要对结果进行排序,则必须将其放入子查询(派生表/ cte)中。
另一个没有FETCH FIRST
子句的方法(从Oracle 8i开始有效):
select id, value, date
from
(
select id, value, date, count(distinct date) over (partition by value) as cnt
from mytable
)
where cnt > 1
order by id, value, date;
不过, forpas的EXISTS
解决方案可能更快。好吧,选择您更喜欢的方法:-)
答案 3 :(得分:0)
对于EXISTS,使用“相关子查询”。因此,我认为这并不比JOIN更好。 但是,Oracle优化器可以将“ EXISTS”重写为JOIN。
我喜欢以经典方式使用JOIN:)
SELECT t1.*
FROM table_values t1, table_values t2
WHERE t1.f_value = t2.f_value
AND t1.f_date <> t2.f_date
ORDER BY 1;