繁体   English   中英

完成 SQL 查询所需的帮助

[英]Assistance needed in finalizing SQL query

我一直在为此示例数据编写 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
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

不确定你需要什么,但可能是这样的:

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

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)
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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM