Oracle SQL 包含要显示的列,但不将其添加到 GROUP BY 中

Oracle SQL Include a column to display without adding it in GROUP BY

我正在尝试查找用户的所有案例变体重复项 table:

SELECT LOWER(EMAIL), COUNT(EMAIL) 
    FROM USERS
    GROUP BY LOWER(EMAIL)
    HAVING COUNT (LOWER(EMAIL)) >= 3;

结果类似于:

Emails                   Count (number of duplicates)
bob@example.com          3   
john.smith@example.com   3 
blah@example.com         4 
james.smith@example.com  3 

问题是我需要每封电子邮件的 ID,我该如何实现?由于 GROUP BY:

,我不能简单地将它添加到 SELECT 语句中
SELECT **ID**, LOWER(EMAIL), COUNT(EMAIL) 
    FROM USERS
    GROUP BY **ID**, LOWER(EMAIL)
    HAVING COUNT (LOWER(EMAIL)) >= 3;

上面会查找重复的电子邮件 ID,这不是我需要的。

试试这个:

SELECT U.*, COUNT(LOWER(EMAIL)) OVER (PARTITION BY (LOWER(EMAIL))) 
    FROM USERS U WHERE LOWER(EMAIL) IN (SELECT LOWER(EMAIL)
    FROM USERS
    GROUP BY LOWER(EMAIL)
    HAVING COUNT (LOWER(EMAIL)) >= 3);

您可以为此使用 analytic count(),在线视图中:

SELECT ID, EMAIL, LOWER(EMAIL), HOW_MANY
FROM (
  SELECT ID, EMAIL, COUNT(*) OVER (PARTITION BY LOWER(EMAIL)) AS HOW_MANY
  FROM USERS
)
WHERE HOW_MANY >= 3
ORDER BY ID;

        ID EMAIL                          LOWER(EMAIL)                     HOW_MANY
---------- ------------------------------ ------------------------------ ----------
         1 bob@example.com                bob@example.com                         3 
         2 Bob@example.com                bob@example.com                         3 
         3 BOB@example.com                bob@example.com                         3 
         4 john.smith@example.com         john.smith@example.com                  3 
         5 John.smith@example.com         john.smith@example.com                  3 
         6 JOHN.smith@example.com         john.smith@example.com                  3 
         7 blah@example.com               blah@example.com                        4 
         8 BLAH@example.com               blah@example.com                        4 
         9 blAH@example.com               blah@example.com                        4 
        10 BLah@example.com               blah@example.com                        4 
        11 james.smith@example.com        james.smith@example.com                 3 
        12 James.smith@example.com        james.smith@example.com                 3 
        13 JAMES.smith@example.com        james.smith@example.com                 3 

SQL Fiddle。分析的好处之一是它只需要点击 table 一次。