从部分重复的行中选择一个值

时间:2014-06-25 13:31:59

标签: sql tsql sql-server-2008-r2

我正在尝试在两行数据之间进行选择,以获得类型的总计数。

Table - Evaluations
EvaluationID (link to minEval_ID and max_EvalID)
EstablishedDelays

Table - Outcome
min_EvalID
max_EvalID
EligTypeRecalc

这是我目前的查询:

SELECT "NewEligType"=
COUNT (*),
SUM (CASE WHEN  a.EligTypeRecalc IN (1,4,5,7) Then 1 Else 0 END) 'Established Condition',
SUM (CASE WHEN  a.EligTypeRecalc=6 Then 1 Else 0 END) 'Established Delay & At-Risk',
SUM (CASE WHEN  a.EligTypeRecalc=2 and b.EstablishedDelays=1 Then 1 Else 0 END) 'Established Delay only: One Delay',
SUM (CASE WHEN  a.EligTypeRecalc=2 and b.EstablishedDelays=2 Then 1 Else 0 END) 'Established Delay only: Two Delays',
SUM (CASE WHEN  a.EligTypeRecalc=2 and b.EstablishedDelays>=3 Then 1 Else 0 END) 'Established Delay only: Three+ Delays',
SUM (CASE WHEN  a.EligTypeRecalc=8 Then 1 Else 0 END) 'Clinical Judgement'

from Outcome a
join Evaluations b
on a.max_EvalID=b.evaluationid and a.min_evalID=b.evaluationID
where a.EligTypeRecalc<>3

我遇到的问题是选择正确的Eval_ID来选择正确的延迟次数而不计算另一次。除非EligTypeRecalc为0,否则与max_EvalID关联的EstablishedDelays是正确的,那么它应该计算与min_EvalID相关的延迟。

到目前为止,我已经提出了这个基本逻辑,但我对如何将其推向下一步感到困惑:

CASE WHEN EligTypeRecalc=max_EvalID
  THEN EstablishedDelays=max_EvalID
  ELSE EstablishedDelays=min_EvalID

奖励积分:我只拥有对数据库的读取权限。

**用于选择相关行并排除其他行的正确查询语法是什么?

感谢您的建议!

2 个答案:

答案 0 :(得分:1)

您可以尝试将您的Evaluations表摘要包装到CTE中,然后将其加入Outcome表。

答案 1 :(得分:0)

这是我使用的代码,有点长:

WITH min_eval AS
(
SELECT
    a.DataMatch,
    a.max_EvalID,
    a.EligTypeRecalc,
    b.evaluationid,
    b.EstablishedDelays
FROM Outcomes a
JOIN Evaluations b
    ON a.min_EvalID=b.evaluationid
    WHERE a.EligTypeRecalc<>3
),
max_eval AS
(
SELECT
    a.DataMatch,
    a.max_EvalID,
    a.EligTypeRecalc,
    b.evaluationid,
    b.EstablishedDelays
FROM Outcomes a
JOIN Evaluations b
    ON a.max_EvalID=b.evaluationid
    WHERE a.EligTypeRecalc<>3
)
SELECT "NewEligType"=
    COUNT (*),
    SUM (CASE WHEN  a.EligTypeRecalc IN (1,4,5,7) THEN 1 ELSE 0 END) 'Established Condition',
    SUM (CASE WHEN  a.EligTypeRecalc=6 THEN 1 ELSE 0 END) 'Established Delay & At-Risk',
    SUM (CASE WHEN  (a.EligTypeRecalc=2 AND a.EstablishedDelays=1) OR (a.EligTypeRecalc=2 AND a.EstablishedDelays=0 AND b.EligTypeRecalc=2 AND b.EstablishedDelays=1) THEN 1 ELSE 0 END) 'Established Delay only: One Delay',
    SUM (CASE WHEN  (a.EligTypeRecalc=2 AND a.EstablishedDelays=2) OR (a.EligTypeRecalc=2 AND a.EstablishedDelays=0 AND b.EligTypeRecalc=2 AND b.EstablishedDelays=2)  THEN 1 ELSE 0 END) 'Established Delay only: Two Delays',
    SUM (CASE WHEN  (a.EligTypeRecalc=2 AND a.EstablishedDelays>=3) OR (a.EligTypeRecalc=2 AND a.EstablishedDelays=0 AND b.EligTypeRecalc=2 AND b.EstablishedDelays>=3)  THEN 1 ELSE 0 END) 'Established Delay only: Three+ Delays',
    SUM (CASE WHEN  a.EligTypeRecalc=8 THEN 1 ELSE 0 END) 'Clinical Judgement'

FROM max_eval a
JOIN min_eval b
    ON a.DataMatch=b.DataMatch