【问题标题】:SQL Server - Select Rows in Derived Table that have count > 1 of value in one columnSQL Server - 在派生表中选择一列中计数> 1的行
【发布时间】:2018-10-08 19:24:26
【问题描述】:

请帮忙。我有以下选择查询,并且只想选择列 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'

【问题讨论】:

    标签: sql-server having derived-table


    【解决方案1】:

    使用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

    【讨论】:

      【解决方案2】:
      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;
      

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

      【讨论】:

        猜你喜欢
        • 2021-08-20
        • 1970-01-01
        • 2013-07-09
        • 2016-01-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-09-28
        • 2015-11-04
        相关资源
        最近更新 更多