Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>While I'd prefer seeing your desired output, perhaps something like this will help get you started:</p> <pre><code>SELECT CONVERT(char(6), AdmissionDate, 112) as CalendarMonth , SUM(DAY(DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,AdmissionDate)+1,0)))-DAY(AdmissionDate)) as TotalLengthOfStayEachMonth, Location FROM VISIT GROUP BY CONVERT(char(6), AdmissionDate, 112), Location </code></pre> <p>Adding the Location will possibly give you duplicate CalendarMonths, but I assume that's ok.</p> <p>EDIT -- </p> <p>I played around with this a little more as I realized some months would be missing dates if the DischargeDate was greater than 1 month over the AdmissionDate, and came up with this -- it uses the spt_values table:</p> <pre><code>select CONVERT(char(6), AdmissionDate+v.number, 112) as CalendarMonth, COUNT(*) Days, Location from Visit t inner join master..spt_values v on v.type='P' and v.number &lt;= DATEDIFF(d, AdmissionDate, DischargeDate) group by Location, CONVERT(char(6), AdmissionDate+v.number, 112) order by CONVERT(char(6), AdmissionDate+v.number, 112), Location </code></pre> <p>Here is the <a href="http://sqlfiddle.com/#!3/4cd3f/1" rel="nofollow">SQL Fiddle</a>.</p> <p>-- Another Edit</p> <p>While reviewing another answer, and not really understanding your situation (need that desired output), if your desired output is 2 days in April for your first record, then you just need to add and v.number &lt;> 0 to the join above -- easy enough, just wasn't sure what you were requesting. This should be the simplest solution:</p> <pre><code>select CONVERT(char(6), AdmissionDate+v.number, 112) as CalendarMonth, COUNT(*) Days, Location from Visit t inner join master..spt_values v on v.type='P' and v.number &lt;= DATEDIFF(d, AdmissionDate, DischargeDate) and v.number &lt;&gt; 0 group by Location, CONVERT(char(6), AdmissionDate+v.number, 112) order by CONVERT(char(6), AdmissionDate+v.number, 112), Location </code></pre> <p>More <a href="http://sqlfiddle.com/#!3/4cd3f/2" rel="nofollow">fiddle</a>.</p> <p>Hope some of this helps.</p> <p>Good luck.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload