Select a distinct row based on the max value of another column SQL Server 2008 R2 -
i have query pulls in information other tables created in query. final output final select statement looks this:
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 ...
what row max(total), in case row total = 12
i have looked @ post cannot seem right. have looked here.
here query producing results:
-- @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 @lace_mstr select q1.mrn , q1.encounter_id , q1.[lace days score] , q1.[acute admit score] , case when q1.visit_count null 0 when q1.visit_count = 1 1 when q1.visit_count = 2 2 when q1.visit_count = 3 3 when q1.visit_count >= 4 4 else 0 end [lace er score] , q1.[cc lace score] ( select distinct t1.encounter_id , t1.mrn , t1.[lace days score] , t1.[acute admit score] , cnt.visit_count , cm.[cc lace score] @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] [total lace] @lace_mstr tried did not right therefore not work --inner join -- ( -- select visit_id -- , max([lace days score]+[lace acute ip score]+[lace er score]+[lace comorbid score]) [total lace] -- @lace_mstr -- group visit_id -- ) groupedlace_mstr on @lace_mstr.visit_id=groupedlace_mstr.visit_id -- , @lace_mstr.[total lace score] = grouped@lace_mstr.[total lace] group visit_id , mrn , [lace days score] , [lace acute ip score] , [lace er score] , [lace comorbid score]
please let me know if there need clarification.
thank you,
assuming grouping should based on visit_id
, mrn
:
;with x ( select visit_id, mrn, ... etc ..., rn = row_number() on (partition visit_id, mrn order [lace days score] + [lace acute ip score] + [lace er score] + [lace comorbid score] desc) @lace_mstr ) select visit_id, mrn, ... etc ... x rn = 1;
Comments
Post a Comment