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
你可以观察到门诊病人ID = 1来自CPT = 1且Revcode = 1而Nonacute ID = 4来自CPT = 4且Revcode = 4
建议我的方式
答案 0 :(得分: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 DEMO 强>
基本上,我们分别获取那些将具有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 DEMO 强>