Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here's my best guess as to what you're trying to do. The first two parts of the CTE are really just to get things into a form similar to what FlyingStreudel suggests. Ideally, you should change the database to match that format instead of doing this through CTEs. That will make this significantly simpler and is better for data integrity as well.</p> <p>Next, I just get the distinct start times in hour increments. You could do that by joining to a Numbers table as well if you can't use CTEs (you didn't mention the version of SQL Server that you're using).</p> <p>Finally, I grab one of those start times at random, using the RAND function and ROW_NUMBER. You'll want to set a good seed value for RAND().</p> <pre><code>;WITH TimesAsTimes AS ( SELECT ScheduleDay, CAST(SUBSTRING(T1.Time1Start, 1, 2) + ':' + SUBSTRING(T1.Time1Start, 3, 2) AS TIME) AS time_start, CAST(SUBSTRING(T1.Time1Stop, 1, 2) + ':' + SUBSTRING(T1.Time1Stop, 3, 2) AS TIME) AS time_stop FROM tbl1 T1 WHERE T1.Time1Start IS NOT NULL UNION ALL SELECT ScheduleDay, CAST(SUBSTRING(T2.Time2Start, 1, 2) + ':' + SUBSTRING(T2.Time2Start, 3, 2) AS TIME) AS time_start, CAST(SUBSTRING(T2.Time2Stop, 1, 2) + ':' + SUBSTRING(T2.Time2Stop, 3, 2) AS TIME) AS time_stop FROM tbl1 T2 WHERE T2.Time2Start IS NOT NULL UNION ALL SELECT ScheduleDay, CAST(SUBSTRING(T3.Time3Start, 1, 2) + ':' + SUBSTRING(T3.Time3Start, 3, 2) AS TIME) AS time_start, CAST(SUBSTRING(T3.Time3Stop, 1, 2) + ':' + SUBSTRING(T3.Time3Stop, 3, 2) AS TIME) AS time_stop FROM tbl1 T3 WHERE T3.Time3Start IS NOT NULL ), PossibleTimeStarts AS ( SELECT ScheduleDay, time_start, time_stop FROM TimesAsTimes TAT UNION ALL SELECT ScheduleDay, DATEADD(hh, 1, time_start) AS time_start, time_stop FROM PossibleTimeStarts PTS WHERE DATEADD(hh, 1, time_start) &lt;= DATEADD(hh, -1, PTS.time_stop) ), PossibleTimesWithRowNums AS ( SELECT ScheduleDay, time_start, ROW_NUMBER() OVER(PARTITION BY ScheduleDay ORDER BY ScheduleDay, time_start) AS row_num, COUNT(*) OVER(PARTITION BY ScheduleDay) AS num_rows FROM PossibleTimeStarts ) SELECT * FROM PossibleTimesWithRowNums WHERE row_num = FLOOR(RAND() * num_rows) + 1 </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. 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