我试图找到同一天发生的重复条目。我有一个数据库表,它基本上只包含ID,USERNAME和DATE_CREATED。
我需要一个大致如此的选择:
SELECT USERNAME,DATE_CREATED
FROM THE_TABLE WHERE {more than one USERNAME exists on date TRUNC(DATE_CREATED)}
是否可以在不通过SELECT创建过程的情况下执行此操作?谢谢你的建议。
答案 0 :(得分:6)
SELECT USERNAME, TRUNC(DATE_CREATED)
FROM THE_TABLE
GROUP BY
USERNAME, TRUNC(DATE_CREATED)
HAVING COUNT(*) > 1;
示例:
SELECT USERNAME, TRUNC(DATE_CREATED)
FROM
(
SELECT 'a' username, sysdate date_created from dual union all
SELECT 'a' username, sysdate date_created from dual union all
SELECT 'b' username, sysdate date_created from dual union all
SELECT 'b' username, sysdate date_created from dual
)
GROUP BY
USERNAME, TRUNC(DATE_CREATED)
HAVING COUNT(*) > 1;
/*
a 2013-06-18 00:00:00
b 2013-06-18 00:00:00
*/
要在输出中获取完整日期,这有点复杂:
SELECT DISTINCT
username
, date_created
FROM the_table ot
WHERE EXISTS
(
SELECT 1
FROM the_table it
WHERE TRUNC(ot.date_created) = TRUNC(it.date_created)
AND ot.username = it.username
GROUP BY
USERNAME, TRUNC(DATE_CREATED)
HAVING COUNT(*) > 1
)
;
/*
a 2013-06-18 12:48:40
b 2013-06-18 12:48:40
*/
表必须访问两次+ DISTINCT关键字是必需的。是的,性能会下降。
答案 1 :(得分:5)
这将在输出中返回完整日期。
SELECT
USERNAME
, DATE_CREATED
FROM
(
SELECT
USERNAME
, DATE_CREATED
, COUNT( *) over ( PARTITION by USERNAME, TRUNC( DATE_CREATED, 'DD') ) cnt
FROM THE_TABLE
)
WHERE cnt > 1
;
答案 2 :(得分:2)
SELECT USERNAME, trunc(DATE_CREATED)
FROM THE_TABLE
group by Username,TRUNC(DATE_CREATED)
having count(1) > 1
答案 3 :(得分:0)
使用Having
select USERNAME, DATE_CREATED
from test
group by USERNAME, DATE_CREATED
Having COUNT(1) > 1