1
Sno ECTCodeDescription  ECTHedisCodeTypeCode
1   Outpatient  CPT
2   Outpatient  RevCode
3   Nonacute inpatient  CPT
4   Nonacute inpatient  RevCode
5   ED  CPT
6   ED  RevCode
7   Acute inpatient CPT
8   Acute inpatient RevCode

在这里我得到这样的结果,我的查询是

SELECT 
    DISTINCT Sno = ROW_NUMBER() OVER (
            ORDER BY ECTCodeDescription DESC
            ),
    EC.ECTCodeDescription,
    CEC.ECTHedisCodeTypeCode
FROM CodeSetHEDIS_ECTCode EC
INNER JOIN CodeSetECTHedisCodeType CEC
    ON EC.ECTHedisCodeTypeID = CEC.ECTHedisCodeTypeID
WHERE ECTHedisTableID = 29 
GROUP BY ECTCodeDescription,
CEC.ECTHedisCodeTypeCode

我怎样才能得到这样的输出:

Sno CODEName            CODEID
1   Outpatient          NULL
2   CPT                 1
3   RevCode             1   
4   Nonacute            NULL    
5   CPT                 4
6   RevCode             4
7   ED                  NULL
8   CPT                 7
9   RevCode             7
10  Acute inpatient     NULL    
11  CPT                 10
12  RevCode             10

您可以观察 CPT = 1 和 Revcode = 1 的门诊 ID = 1 和 CPT = 4 和 Revcode = 4 的非急性 ID = 4

建议我的方式

4

1 回答 1

0

假设您的表结构和数据类似于This Example,您的新查询可能如下所示:

;WITH CTE_distinct AS 
(
    SELECT ECTCodeDescription FROM CodeSetHEDIS_ECTCode
    GROUP BY ECTCodeDescription
)
, CTE_all AS 
(
    SELECT ECTCodeDescription AS CodeName, 0 AS CodeLevel, ECTCodeDescription AS MainCode  
    FROM CTE_distinct d
    UNION ALL
    SELECT t.ECTHedisCodeTypeCode AS CodeName, 1 AS CodeLevel, c.ECTCodeDescription AS MainCode
    FROM CTE_distinct d
    INNER JOIN dbo.CodeSetHEDIS_ECTCode c ON d.ECTCodeDescription = c.ECTCodeDescription
    INNER JOIN dbo.CodeSetECTHedisCodeType t ON c.ECTHedisCodeTypeID = t.ECTHedisCodeTypeID
)
,CTE_Numbers AS 
(
    SELECT 
        ROW_NUMBER() OVER (ORDER BY MainCode DESC, CodeLevel) AS Sno
        , *
    FROM CTE_all
)
SELECT sno, CodeName, NULL AS COdeID FROM CTE_Numbers 
WHERE CodeLevel = 0
UNION
SELECT n2.sno, n2.CodeName, n1.sno AS CodeID FROM CTE_Numbers n1
inner JOIN CTE_Numbers n2 ON n1.MainCode = n2.MainCode AND n1.CodeLevel = 0 AND n2.CodeLevel = 1
ORDER BY Sno

SQLFiddle 演示

基本上,我们分别得到那些将具有 CodeID NULL 的那些和那些不会将它们合并在一起以进行编号的那些。最后将它们分开并再次合并以在 CodeID 列中获得正确的值。

最后一部分也可以用子查询而不是联合来完成。

SELECT sno, CodeName
    , CASE WHEN CodeLevel = 0 THEN  NULL 
           ELSE (SELECT sno FROM CTE_Numbers c2 WHERE c2.MainCode = c1.MainCode AND c2.CodeLevel = 0) 
    END AS CodeID
FROM CTE_Numbers c1
ORDER BY Sno

SQLFiddle 演示

于 2013-05-24T11:31:55.367 回答