我有一个查询,它从查询中创建的其他表中提取信息。最终select语句的最终输出如下所示:
VISIT_ID | MRN | DAYS SCORE | IP SCORE | ER SCORE | CC SCORE | TOTAL
123456 | 123 | 3 | 3 | 2 | 0 | 8
123456 | 123 | 3 | 3 | 2 | 2 | 10
123456 | 123 | 3 | 3 | 2 | 4 | 12
...
我想做的是获取MAX(TOTAL)行,在这种情况下是TOTAL = 12
我已经看过这个post,但似乎无法做到正确。我也看了here.
以下是产生结果的查询:
-- @LACE_MSTR TABLE DECLARATION ###################################//
DECLARE @LACE_MSTR TABLE(
MRN VARCHAR(200)
, VISIT_ID VARCHAR(200)
, [LACE DAYS SCORE] INT
, [LACE ACUTE IP SCORE] INT
, [LACE ER SCORE] INT
, [LACE COMORBID SCORE] INT
)
--###################################################################//
INSERT INTO @LACE_MSTR
SELECT
Q1.MRN
, Q1.ENCOUNTER_ID
, Q1.[LACE DAYS SCORE]
, Q1.[ACUTE ADMIT SCORE]
, CASE
WHEN Q1.VISIT_COUNT IS NULL THEN 0
WHEN Q1.VISIT_COUNT = 1 THEN 1
WHEN Q1.VISIT_COUNT = 2 THEN 2
WHEN Q1.VISIT_COUNT = 3 THEN 3
WHEN Q1.VISIT_COUNT >= 4 THEN 4
ELSE 0
END AS [LACE ER SCORE]
, Q1.[CC LACE SCORE]
FROM
(
SELECT
DISTINCT T1.ENCOUNTER_ID
, T1.MRN
, T1.[LACE DAYS SCORE]
, T1.[ACUTE ADMIT SCORE]
, CNT.VISIT_COUNT
, CM.[CC LACE SCORE]
FROM @T1 T1
LEFT OUTER JOIN @CNT CNT
ON T1.MRN = CNT.MRN
JOIN @CM CM
ON CM.[MRN CM] = T1.[MRN]
) Q1
SELECT DISTINCT VISIT_ID
, MRN
, [LACE DAYS SCORE]
, [LACE ACUTE IP SCORE]
, [LACE ER SCORE]
, [LACE COMORBID SCORE]
, [LACE DAYS SCORE]+[LACE ACUTE IP SCORE]+[LACE ER SCORE]+[LACE COMORBID SCORE] AS [TOTAL LACE]
FROM @LACE_MSTR
Tried this but I did not do it right therefore it does not work
--INNER JOIN
-- (
-- SELECT VISIT_ID
-- , MAX([LACE DAYS SCORE]+[LACE ACUTE IP SCORE]+[LACE ER SCORE]+[LACE COMORBID SCORE]) AS [TOTAL LACE]
-- FROM @LACE_MSTR
-- GROUP BY VISIT_ID
-- ) GROUPEDLACE_MSTR ON @LACE_MSTR.VISIT_ID=GROUPEDLACE_MSTR.VISIT_ID
-- AND @LACE_MSTR.[TOTAL LACE SCORE] = GROUPED@LACE_MSTR.[TOTAL LACE]
GROUP BY VISIT_ID
, MRN
, [LACE DAYS SCORE]
, [LACE ACUTE IP SCORE]
, [LACE ER SCORE]
, [LACE COMORBID SCORE]
如果需要澄清,请告诉我。
谢谢,
答案 0 :(得分:1)
假设分组应基于VISIT_ID
和MRN
:
;WITH x AS
(
SELECT VISIT_ID, MRN, ... etc ...,
rn = ROW_NUMBER() OVER (PARTITION BY VISIT_ID, MRN
ORDER BY [LACE DAYS SCORE] + [LACE ACUTE IP SCORE]
+ [LACE ER SCORE] + [LACE COMORBID SCORE] DESC)
FROM @LACE_MSTR
)
SELECT VISIT_ID, MRN, ... etc ...
FROM x WHERE rn = 1;