Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You can use a Calendar table defining then weeks and join it to your data.</p> <p>I've created a <a href="http://sqlfiddle.com/#!3/dc8e1/6" rel="nofollow">sql fiddle</a> for the following:</p> <pre><code>CREATE TABLE Calendar_Weeks ( week_start_date date, week_end_date date ) CREATE TABLE Sample_Data ( id int, start_date date, end_date date ) INSERT Calendar_Weeks (week_start_date, week_end_date) VALUES ('2011-04-18','2011-04-24') INSERT Calendar_Weeks (week_start_date, week_end_date) VALUES ('2011-04-25','2011-05-01') INSERT Calendar_Weeks (week_start_date, week_end_date) VALUES ('2011-05-02','2011-05-08') INSERT Calendar_Weeks (week_start_date, week_end_date) VALUES ('2011-05-09','2011-05-15') INSERT Calendar_Weeks (week_start_date, week_end_date) VALUES ('2011-05-16','2011-05-22') INSERT Calendar_Weeks (week_start_date, week_end_date) VALUES ('2011-05-23','2011-05-29') INSERT Sample_Data (id, start_date, end_date) VALUES (1, '2011-04-25','2011-05-08') INSERT Sample_Data (id, start_date, end_date) VALUES (2, '2011-04-23','2011-05-27') SELECT id, week_start_date, week_end_date FROM Sample_Data CROSS JOIN Calendar_Weeks WHERE week_start_date BETWEEN start_date AND end_date UNION SELECT id, week_start_date, week_end_date FROM Sample_Data CROSS JOIN Calendar_Weeks WHERE week_end_date BETWEEN start_date AND end_date </code></pre> <p>I have to admit the <code>UNION</code> of the queries <em>feels</em> a bit of a hack to include rows at the start or end of the set, so you might prefer to use Ravi Singh's solution.</p> <p>You can also use <code>INNER JOIN</code> if you like:</p> <pre><code>SELECT id, week_start_date, week_end_date FROM Sample_Data INNER JOIN Calendar_Weeks ON week_start_date BETWEEN start_date AND end_date UNION SELECT id, week_start_date, week_end_date FROM Sample_Data INNER JOIN Calendar_Weeks ON week_end_date BETWEEN start_date AND end_date </code></pre>
    singulars
    1. This table or related slice is empty.
    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. 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.
    3. 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