我需要重写以下查询以避免子查询。我该怎么做....下面的查询中有两个子查询
select
cc1.claimid as claimid,
cc1.createdate as createdate,
cc1.condcode as condition_cd1,
cc2.condcode as condition_cd2,
cc3.condcode as condition_cd3
from claimcond cc1 (nolock)
left outer join claimcond cc2 (nolock) on
cc1.claimid = cc2.claimid
and cc2.condcode = (select min(condcode) from claimcond cc (nolock) where cc1.claimid = cc.claimid)
and cc1.condcode <> cc2.condcode
left outer join claimcond cc3 (nolock) on
cc1.claimid = cc3.claimid
and cc3.condcode in (select min(condcode) from claimcond cc (nolock) where cc1.claimid = cc.claimid
and ((cc.condcode > cc2.condcode)))
and cc1.condcode <> cc3.condcode
ORDER BY cc1.claimid, cc1.condcode DESC
答案 0 :(得分:0)
存在:
select
cc1.claimid as claimid,
cc1.createdate as createdate,
cc1.condcode as condition_cd1,
cc2.condcode as condition_cd2,
cc3.condcode as condition_cd3
from claimcond cc1 (nolock)
left outer join claimcond cc2 (nolock) on
cc1.claimid = cc2.claimid
and cc1.condcode <> cc2.condcode
left outer join claimcond cc3 (nolock) on
cc1.claimid = cc3.claimid
and ((cc.condcode > cc2.condcode)))
and cc1.condcode <> cc3.condcode
WHERE EXISTS (
SELECT '1'
FROM claimcond cc (nolock)
WHERE cc1.claimid = cc.claimid and -- Maybe OR
cc2.claimID = cc.claimid )
ORDER BY cc1.claimid, cc1.condcode DESC
答案 1 :(得分:0)
你应该看看它的表现如何:
DECLARE @MinCondCode TABLE (
claimid INT, --datatype correct?
MinCode1 VARCHAR(20) NULL, --datatype correct?
MinCode2 VARCHAR(20) NULL --datatype correct?
)
INSERT INTO @MinCondCode (claimid,MinCode1)
select claimid,min(condcode)
from claimcond cc (nolock)
group by claimid
UPDATE MinCondCode
SET MinCode2=(
select min(condcode)
from claimcond cc (nolock)
WHERE cc.condcode > MinCondCode.MinCode1
AND MinCondCode.claimid = cc.claimid
)
select
cc1.claimid as claimid,
cc1.createdate as createdate,
cc1.condcode as condition_cd1,
cc2.condcode as condition_cd2,
cc3.condcode as condition_cd3
from claimcond cc1 (nolock)
INNER JOIN @MinCondCode mn on mn.claimid=cc1.claimid
left outer join claimcond cc2 (nolock) on cc1.claimid = cc2.claimid
and cc2.condcode = mn.MinCode1
and cc1.condcode <> cc2.condcode
left outer join claimcond cc3 (nolock) on cc1.claimid = cc3.claimid
and cc3.condcode = mn.MinCode2
and cc1.condcode <> cc3.condcode
ORDER BY cc1.claimid, cc1.condcode DESC