sql server - SELECT DISTINCT creates multiple rows -


complete sql newbie please kind. have following statement:

select distinct      ttmpo."operationrecordid"     , ttmpo."casenotenumber"     , ttmpo."datetimebooked"     , tspps."startdate"     , aeadm."visit date"     , aeadm."visit time"     , aeadm."episode number"     , aeadm.[visit number]        (("theatrelive"."dbo"."tblspplannedsession" tspps  left outer join      "theatrelive"."dbo"."tbltmplannedoperation" ttmpo on tspps."sessionrecordid" = ttmpo."sessionrecordid")  left outer join      "theatrelive"."dbo"."tbltmactualoperation" ttmao on ttmpo."operationrecordid" = ttmao."operationrecordid")  left outer join      "theatrelive"."dbo"."cavaeadmissions" aeadm on ttmao."casenotenumber"=aeadm."crn" collate database_default      tspps."startdate" < dateadd(day, 2, aeadm."visit date")      , aeadm."visit date" < tspps."startdate"  

i used distinct notice multiple rows operationrecordid appearing when more 1 episode number appears. tried adding select top 1 complete logic found in where clause need added ran exceptionally slowly.

the where clause there narrow down results set , looking dates within 2 days of each other.

essentially, each distinct operationrecordid need both latest episode number , if more 1 visit number appears, highest visit number also. both of these should able selected max clause.

thoughts?

the distinct keyword applies columns selected - not column appears before. sounds might need max function group or, depending on how complex criteria are, inline table.

something like

select      ttmpo."operationrecordid"     , ttmpo."casenotenumber"     , ttmpo."datetimebooked"     , tspps."startdate"     , aeadm."visit date"     , aeadm."visit time"     , max(aeadm."episode number")     , max(aeadm.[visit number])        (("theatrelive"."dbo"."tblspplannedsession" tspps  left outer join      "theatrelive"."dbo"."tbltmplannedoperation" ttmpo on tspps."sessionrecordid" = ttmpo."sessionrecordid")  left outer join      "theatrelive"."dbo"."tbltmactualoperation" ttmao on ttmpo."operationrecordid" = ttmao."operationrecordid")  left outer join      "theatrelive"."dbo"."cavaeadmissions" aeadm on ttmao."casenotenumber"=aeadm."crn" collate database_default      tspps."startdate" < dateadd(day, 2, aeadm."visit date")      , aeadm."visit date" < tspps."startdate"  group ttmpo."operationrecordid"     , ttmpo."casenotenumber"     , ttmpo."datetimebooked"     , tspps."startdate"     , aeadm."visit date"     , aeadm."visit time" 

Comments

Popular posts from this blog

java - Andrioid studio start fail: Fatal error initializing 'null' -

android - Gradle sync Error:Configuration with name 'default' not found -

StringGrid issue in Delphi XE8 firemonkey mobile app -