最终确定SQL查询时需要帮助

时间:2016-05-14 15:32:33

标签: sql sql-server sql-server-2008

我很难为这个示例数据编写SQL代码

Dummy Col   AcctSK      AcctrelatedSK   
--------------------------------------
9999        11465399    -1          
9999        11465399    11401099    

在上面的示例数据中,我有一个acctsk,但在实际编写的代码中,我正在返回更多不同的acctsk值,但行为与上面提到的相同。

我想要实现的是,如果某些acctsk的计数大于或等于2,则仅返回Acctrelatedsk中除-1以外的值。当只有一个AccountSk时,代码返回正确的结果,但是当多个Acctsk时,我无法确定该部分。

更多样本数据

9999 11465399 -1
9999 11465399 11401099
9999 11465404 -1
9999 11465404 11401099
9999 11465405 -1
9999 11465405 11401099
9999 11465440 -1
9999 11465440 11401665

预期结果

9999 11465399 11401099
9999 11465404 11401099
9999 11465405 11401099
9999 11465440 11401665

4 个答案:

答案 0 :(得分:0)

declare @DummyTable Table (DummyId int, Acctsk int, AcctrelatedSK int)

insert into @DummyTable 
values(9999, 11465399, -1),
(9999, 11465399, 11401099)

select top 1 dt.Acctsk, dt.AcctrelatedSK from (
select Acctsk
from @DummyTable dt
Group By Acctsk 
Having Count(Acctsk) >= 2) as temp
join @DummyTable dt on dt.Acctsk = temp.Acctsk
where dt.AcctrelatedSK != -1

答案 1 :(得分:0)

不确定你需要什么,但也许是这样的:

select * from (
  select
    *, dense_rank() over (partition by AcctSK order by case when AcctrelatedSK = -1 then 1 else 0 end) as RANK
  from
    yourtable
) X where (AcctrelatedSK != -1 or RANK = 1)

排名处理选择其他行或-1当它是唯一的行

答案 2 :(得分:0)

DECLARE @temp TABLE (
    AcctSK int,
    AcctrelatedSK int,
    Count int
);

INSERT INTO @temp (AcctSK, AcctrelatedSK, Count)
SELECT 
    AcctSK,
    AcctrelatedSK,
    ( SELECT count(1) FROM DataTable WHERE AcctSK = OriginalData.AcctSK ) AS Count
FROM DataTable AS OriginalData 

SELECT *
FROM @temp
WHERE Count = 1
  OR (Count >= 2 AND AcctrelatedSK > -1)

答案 3 :(得分:0)

SELECT x.*
FROM (
SELECT *,
row_number() OVER (PARTITION BY AcctSK ORDER BY CASE WHEN AcctrelatedSK = -1 THEN 1 ELSE 0 END) rn
FROM YourTable) x
WHERE x.rn = 1;