我试图通过SQL Server中的SQL实现以下目的。
我有一个源表,其中包含以下记录:
RCD
6和7条记录(如果存在)RCD
8和9,我需要检查相同的PKey
:
Rkey
相同,如果是,那么我只需要检索任何记录RCD
不同,{li>对于PKey
8和9代表Rkey
,那么我需要检索这两者。
我尝试过这样做,但我不知道如何做到这一点,任何人都可以建议如何在SQL for SQL Server中实现这一点。
答案 0 :(得分:0)
如果我理解正确,您可以使用窗口函数来获取所需的基本信息。其余的只是逻辑:
select t.*
from (select t.*,
min(rkey) over (partition by rcd, pkey) as min_rkey,
max(rkey) over (partition by rcd, pkey) as max_rkey,
row_number() over (partition by rcd, pkey, rkey order by rkey) as seqnum
from t
) t
where rcd in (6, 7) or
( (rcd in (8, 9) and min_rkey = max_rkey and seqnum = 1) or
(rcd in (8, 9) and min_rkey <> max_rkey)
);
编辑:
我怀疑在8/9条件下你需要的不仅仅是pkey
:
select t.*
from (select t.*,
min(rkey) over (partition by rcd, pkey) as min_rkey,
max(rkey) over (partition by rcd, pkey) as max_rkey,
row_number() over (partition by rcd, pkey, rkey order by rkey) as seqnum,
count(*) over (partition by rcd, pkey) as cnt
from t
) t
where rcd in (6, 7) or
( (rcd in (8, 9) and cnt > 1 and min_rkey = max_rkey and seqnum = 1) or
(rcd in (8, 9) and cnt > 1 and min_rkey <> max_rkey)
);
答案 1 :(得分:0)
如果我理解正确,这就是你要找的东西:
SELECT RAKey, RCD, Pkey, Rkey, Akey
FROM Source s
WHERE s.RCD IN (6,7)
UNION
SELECT RAKey, RCD, Pkey, Rkey, Akey FROM
(SELECT
row_number() over(partition by Pkey order by newid()) as rowID,
*
FROM Source s2
WHERE RCD IN (8,9)
AND (EXISTS (SELECT TOP 1 1 FROM Source WHERE Pkey = s2.Pkey AND s2.RCD = 8 AND RCD = 9 AND RKey = s2.Rkey)
OR EXISTS (SELECT TOP 1 1 FROM Source WHERE Pkey = s2.Pkey AND s2.RCD = 9 AND RCD = 8 AND RKey = s2.Rkey))
) s2
WHERE rowID = 1
UNION
SELECT RAKey, RCD, Pkey, Rkey, Akey
FROM Source s3
WHERE RCD IN (8,9)
AND (EXISTS (SELECT TOP 1 1 FROM Source WHERE Pkey = s3.Pkey AND s3.RCD = 8 AND RCD = 9 AND RKey <> s3.Rkey)
OR EXISTS (SELECT TOP 1 1 FROM Source WHERE Pkey = s3.Pkey AND s3.RCD = 9 AND RCD = 8 AND RKey <> s3.Rkey))
此外,您的目标插图与您在下面的标准相矛盾:
答案 2 :(得分:0)
SELECT *
FROM [SOURCE] WHERE RCD IN (6,7)
UNION ALL
SELECT H.RAKEY,H.RCD,H.pkey,H.rkey
FROM
(
SELECT ROW_NUMBER()OVER (PARTITION BY PKEY,rkey,Value ORDER BY RAKEY)
RNO,A.*
FROM
(
SELECT H.RAKEY,H.RCD,H.pkey,H.rkey,CASE WHEN H.RAKEY < K.RAKEY THEN
H.RAKEY ELSE K.RAKEY END Value
FROM [SOURCE] H
LEFT JOIN [SOURCE] K
ON H.pkey = K.pkey AND H.rkey = K.rkey AND H.RCD <> K.RCD AND K.RCD IN
(8,9)
WHERE H.RCD IN (8,9)
)A
)H WHERE H.RNO = 1
ORDER BY 1`
答案 3 :(得分:0)
SELECT H.RAKEY,H.RCD,H.pkey,H.rkey
FROM
(
SELECT ROW_NUMBER()OVER (PARTITION BY PKEY,rkey,Value ORDER BY RCD)
RNO,A.*
FROM
(
SELECT H.RAKEY,H.RCD,H.pkey,H.rkey,MIN(H.RCD) OVER (Partition by
H.PKey,K.rkey) Value
FROM [SOURCE] H
LEFT JOIN [SOURCE] K
ON H.pkey = K.pkey AND H.rkey = K.rkey AND H.RCD <> K.RCD AND K.RCD IN
(6,8,9)
WHERE H.RCD IN (6,8,9)
)A
)H WHERE H.RNO = 1
嗨Gaur,我希望上面的查询适用于您的问题“我想要做的是,如果RCD 6和RCD 8和9的PKey和RKey值相同,我想保留RCD6的详细信息并放弃休息细节。“