如何在sql server中的另一列上获取具有多个值的行?

时间:2014-10-22 19:45:41

标签: sql sql-server

我这里有一个脚本来获取拥有多个所有者的所有帐号,但我想删除那些出现1 account_number = 1 account_owner的行。我希望获得的记录显示1 account_number> = one account_owner。

select ACCT_NUMBER, ACCT_OWNER from [DW].[ACCT DETAILS] WITH(NOLOCK) 
where ACCT_NUMBER in (select distinct(ACCT_NUMBER)
                      from [DW].[TDMA_DIM_DETAILS] WITH(NOLOCK)
                      group by ACCT_NUMBER
                      )
group by ACCT_NUMBER, ACCT_OWNER 

以下是结果..

    ACCT_NUMBER  ACCT_OWNER
    1359180      Spearman, John
    1359190      Grifman, Karen
    1359210      Spearman, John

    1359220      Adams, Craig
    1359220      Biga, Lou
    1359220      Wright, Gerald

    1359230      Levine, Renee
    1359250      Reitwiesner, John
    1359260      Skowronski, Cindi

    1359510      Cordova, Diana
    1359510      Macfarlane, Linda
    1359510      Marquez, Suzanne

我希望看到的结果类似于我从帐号1359220和1359510获得的结果,因为还有其他帐号有多个所有者。

我尝试过使用(计数(不同的ACCT_OWNER)> 1但它没有帮助。

2 个答案:

答案 0 :(得分:3)

;WITH CTE AS
(
    SELECT  ACCT_NUMBER, 
            ACCT_OWNER
    FROM [DW].[ACCT DETAILS]
    WHERE ACCT_NUMBER IN (  SELECT ACCT_NUMBER
                            FROM [DW].[TDMA_DIM_DETAILS])
    GROUP BY ACCT_NUMBER, 
             ACCT_OWNER
), CTE2 AS
(
    SELECT  *,
            N = COUNT(*) OVER(PARTITION BY ACCT_NUMBER)
    FROM CTE
)
SELECT *
FROM CTE2
WHERE N > 1

答案 1 :(得分:0)

SELECT
  [ACCT_NUMBER]
 ,[ACCT_OWNER]
 ,COUNT(*) OVER(PARTITION BY ACCT_NUMBER)
FROM [DW].[ACCT DETAILS] a
INNER JOIN [DW].[TDMA_DIM_DETAILS] b
  ON a.[ACCT_NUMBER] = b.[ACCT_NUMBER]
GROUP BY [ACCT_NUMBER],[ACCT_OWNER]
EXCEPT
SELECT
  [ACCT_NUMBER]
 ,[ACCT_OWNER]
 ,1
FROM [DW].[ACCT DETAILS]