SQL 服务器 - Select 派生 Table 中一列中值的计数 > 1 的行

SQL Server - Select Rows in Derived Table that have count > 1 of value in one column

请帮忙。我有以下 Select 查询,并且只想 select 列 A.Name 重复超过 1 次的行:

SELECT
    A.Payer,
    A.PaymentDate,
    A.Name
FROM 
    (SELECT
         T.InstitutionRoleXrefLongName AS 'Payer',
         T.PaymentDate AS 'PaymentDate',
         T.FullName AS 'Name'
     FROM 
         Transfer T
     UNION ALL
     SELECT
         T.InstitutionRoleXrefLongName AS 'Payer',
         T.PaymentDate AS 'PaymentDate',
         T.FullName AS 'Name'
     FROM 
         TransferClosed T) A
WHERE 
    PaymentDate BETWEEN '20180101' AND '20180331 23:59:59'

使用 CTEself join 得到大于 1 的 count

你可以试试这个。

 ;with CTE AS (
    SELECT
        A.Payer,
        A.PaymentDate,
        A.Name
    FROM (
        SELECT
            T.InstitutionRoleXrefLongName AS 'Payer',
            T.PaymentDate AS 'PaymentDate',
            T.FullName AS 'Name'
        FROM Transfer T
    UNION ALL
        SELECT
            T.InstitutionRoleXrefLongName AS 'Payer',
            T.PaymentDate AS 'PaymentDate',
            T.FullName AS 'Name'
        FROM TransferClosed T
    ) A
    WHERE PaymentDate Between '20180101' AND '20180331 23:59:59'
)
select t2.*
from (
    SELECT name,count(1) totle 
    FROM CTE
    GROUP BY Name
) t1 inner join CTE t2 
ON t1.totle > 1 and t1.Name = t2.Name

sqlfiddle CTE 模拟你的结果集

sqlfiddle:http://sqlfiddle.com/#!18/cc68f/9

WITH Payments AS (
    SELECT
        A.Payer, A.PaymentDate, A.Name,
        COUNT(*) OVER (PARTITION BY A.Name) AS NameCount
    FROM (
        SELECT
            T.InstitutionRoleXrefLongName AS Payer,
            T.PaymentDate AS PaymentDate,
            T.FullName AS Name
        FROM Transfer T
        UNION ALL
        SELECT
            T.InstitutionRoleXrefLongName AS Payer,
            T.PaymentDate AS PaymentDate,
            T.FullName AS Name
        FROM TransferClosed T
    ) A
    WHERE PaymentDate Between '20180101' AND '20180331 23:59:59'
)
SELECT * FROM Payments WHERE Name_Count > 1;

您可能会发现,通过在并集的两侧复制该日期过滤器,查询性能会更好。只是一个想法。