SQL Count(*),然后显示这些结果的列

时间:2019-07-11 12:31:41

标签: sql oracle count

这可能是一个简单的问题,但我对此有些挣扎。

SELECT
    DAY, PLACEMENT, SECLEVEL, COUNT(*)
FROM
    SECPEOPLE
GROUP BY
    DAY, PLACEMENT, SECLEVEL
HAVING 
    COUNT(*) > 1

这将返回重复的人,这些人在同一地点,同一天和同一secLevel。

这一切都很好,很好,问题是我如何完成此查询,以便代替此信息,我获得重复的唯一ID?

同一张表的“ ID”列是唯一的。

4 个答案:

答案 0 :(得分:3)

您可以使用分析功能来做到这一点:

SELECT id, day, placement, seclevel
FROM (
    SELECT id, day, placement, seclevel, 
           count(*) over (partition by day, placement, seclevel) as cnt
    FROM secpeople
) t
WHERE cnt > 1;

答案 1 :(得分:0)

一种简单的方法使用exists

SELECT p.*
FROM SECPEOPLE p
WHERE EXISTS (SELECT 1
              FROM SECPEOPLE p2
              WHERE p2.day = p.day AND
                    p2.PLACEMENT = p.PLACEMENT AND
                    p2.SECLEVEL = p.SECLEVEL AND
                    p2.<id> <> p.<id>
              )
ORDER BY DAY, PLACEMENT, SECLEVEL

答案 2 :(得分:0)

与cte一起使用

with cte as
(
   SELECT
        DAY, PLACEMENT, SECLEVEL, COUNT(*)
    FROM
        SECPEOPLE
    GROUP BY
        DAY, PLACEMENT, SECLEVEL
    HAVING 
        COUNT(*) > 1
    ) select a.id from cte join SECPEOPLE a on cte.DAY=a.DAY and cte.PLACEMENT=a.PLACEMENT and cte.SECLEVEL=a.SECLEVEL

答案 3 :(得分:0)

或者,如果您想使用自己编写的查询

SELECT *
  FROM secpeople
 WHERE (day, placement, seclevel) IN 
   (-- this is your query
    SELECT DAY, PLACEMENT, SECLEVEL
    FROM SECPEOPLE
    GROUP BY DAY, PLACEMENT, SECLEVEL
    HAVING COUNT (*) > 1
   )