need help a query in sql server 2008 -
hi have doubt in sql server
table : patient patientno | refdoctor| loccode | status | sdate 100 | 31 |10 | 1 | 2012-05-03 100 | 32 |10 | 1 |1997-02-04 100 | 36 |10 | 1 |2014-09-16 100 |35 |10 | 1 |2013-05-03 100 | 50 |10 | 1 | 1988-05-08 100 | 20 |10 | 2 |2015-02-05 table : targetpatient patientno | refdoctor| loccode | status | sdate 100 | 21 | 10 | 2 | 2004-05-18 100 | 23 | 10 | 2 |2005-07-25 100 | 24 | 10 | 2 | 2006-06-22 100 | 26 | 10 | 2 |2012-05-14 100 | 28 |10 | 2 |2013-05-03 100 |29 |10 | 2 | 2014-09-26 100 | 33 | 10 | 2 | 2012-10-22 100 | 39 | 10 | 2 |2002-12-13 100 |41 | 10 | 2 |2012-05-13
here want output patient table relates status
statusvalue=5's sdate less or equal checkvalue=2's sdate , difference between dates should less 30days given count if condition not fall count must return zero(0)
select o.patientno,o.loccode,o.status,o.sdate, count(*) cnt patient o join targetpatient t on o.patientno=t.patientno , o.loccode=t.loccode , o.status in('1') , t.status in('2') , o.sdate<=t.sdate , datediff(dd,o.sdate,t.sdate)<=30 group o.patientno,o.loccode,o.status,o.sdate based on above query got result below: patientno | loccode | status | sdate | count 100 | 10 | 1 |2012-05-03 | 2 100 | 10 | 1 |2013-05-03 | 1 100 | 10 | 1 |2014-09-16 | 1 want expected result below patientno | loccode | status | sdate | count 100 | 10 | 1 |2012-05-03 | 2 100 | 10 | 1 |2013-05-03 | 1 100 | 10 | 1 |2014-09-16 | 1 100 | 10 | 1 | 1997-02-04 | 0 100 | 10 |1 | 1988-05-08 | 0
please tell me how write query achive task in sql server .
if want include records doesn't have matches in joined table you'll want use left join
instead , count
on column in joined table instead this:
select o.patientno,o.loccode,o.status,o.sdate, count(t.sdate) cnt patient o left join targetpatient t on o.patientno = t.patientno , o.loccode = t.loccode , o.status in('1') , t.status in('2') , o.sdate <= t.sdate , datediff(dd,o.sdate,t.sdate) <= 30 group o.patientno,o.loccode,o.status,o.sdate
a left join
return rows table on left side (patient
in case) plus matching rows right-hand side table. rows doesn't have matches in right-hand side table null values.
Comments
Post a Comment