如何返回按列A分组的记录在列B中具有不同的值

时间:2015-04-24 02:55:32

标签: sql-server sql-server-2008 select group-by common-table-expression

原谅标题,但这就是我在表#RISK

中的内容
ACCT_NUM  RISK
1234       5
007       10
007        1
37947      3

我希望输出为 -

ACCT_NUM  RISK
007        10
007        1

这是我试过的 -

;WITH C AS(
    SELECT ROW_NUMBER() OVER (PARTITION BY ACCT_NUM ORDER BY ACCT_NUM, RISK) AS Rn
           ,ACCT_NUM, RISK
    FROM #RISK 
    WHERE NOT EXISTS(
    SELECT ACCT_NUM,RISK FROM #RISK GROUP BY ACCT_NUM,RISK)

)
SELECT *
FROM C

但是我的查询没有返回任何结果。我做错了什么?

3 个答案:

答案 0 :(得分:0)

这是你想要的吗?

select acct_num, risk
from (select r.*,
             min(risk) over (partition by acct_num) over minrisk,
             max(risk) over (partition by acct_num) over maxrisk
      from #risk r
     ) r
where minrisk <> maxrisk;

答案 1 :(得分:0)

我们可以通过使用count和Row_number函数来实现这个结果

declare @t table (AcctNum varchar(10),risk int)
insert into @t(AcctNum,risk)values
('1234',5),
('007',10),
('007',1),
('37947',3)


;with cte as (
select AcctNum,risk,COUNT(AcctNum)OVER(PARTITION BY AcctNum )RN from @t )
select AcctNum,risk from cte WHERE RN = 2

答案 2 :(得分:0)

可能有帮助

SELECT ACCT_NUM,RISK FROM #RISK
where ACCT_NUM=(
SELECT ACCT_NUM FROM #RISK
GROUP BY ACCT_NUM 
HAVING COUNT(*)>1)