-3

I want to find the 3rd available appointment from a list of appointments.

MySql database has rows with RotaType, Date and UnusedSlots as columns

I want to do something like

 $sql3 = "SELECT * FROM `UsageDailyUnusedSlots` WHERE Date >= '$Today' AND RotaType LIKE '%Derm%' AND UnusedSlots > 0 AND RotaType NOT LIKE '%- Y%' AND RotaType NOT LIKE '%- y%' ORDER BY Date LIMIT 1 OFFSET 2;";

however this would find me the 3rd day with available slots, not the 3rd slot.

I could do a complicated loop of each row, adding up the value with each iteration/loop and echoing the value when the total >= 3, however I feel there must be a better way.

Here is a scenario

Table of Data

My sql code above would select 31/01/2020 as the 3rd day with UnusedSlots on, however I want it to select 30/01/2020 as the date as that's when the 3rd next unused appointment is

Any thoughts?

Thanks

The Impaler
  • 45,731
  • 9
  • 39
  • 76
Henry Aspden
  • 1,863
  • 3
  • 23
  • 45

2 Answers2

0
WITH cte AS (
    SELECT *,
           SUM(UnusedSlots) OVER (ORDER BY Date) cnt
    FROM `UsageDailyUnusedSlots` 
    WHERE Date >= '$Today' 
    AND RotaType LIKE '%Derm%' 
    AND UnusedSlots > 0 
    AND RotaType NOT LIKE '%- Y%' 
    AND RotaType NOT LIKE '%- y%' )
SELECT *
FROM cte
WHERE cnt >= 3
ORDER BY cnt
LIMIT 1
Akina
  • 39,301
  • 5
  • 14
  • 25
0

You can use windows functions to find the specific location of the slot you want. For example:

select *
from (
  select
    *,
    sum(`UnusedSlots`) over(order by Date 
      rows between unbounded preceding and 1 preceding) as previous_slots,
    sum(`UnusedSlots`) over(order by Date) as current_slots
  from `UsageDailyUnusedSlots`
  where Date >= '2020-01-15' 
    and RotaType like '%Derm%' 
    and RotaType not like '%- Y%' 
) x
where previous_slots < 3 and current_slots >= 3
The Impaler
  • 45,731
  • 9
  • 39
  • 76