Question

Suppose there are 25 groups of programmers, with 5-100 programmers in each group. Each group of programmers is tasked with writing the query that this question refers to. In response to this task, many programmers in each group begins drinking heavily. Each group has a stocked bar consisting of:

  • Whiskey
  • Vodka
  • Beer
  • Water

Every time a programmer finishes a drink, a new row is added to the table including:

  • Time the drink was finished
  • Group ID
  • Programmer ID
  • Type of drink consumed

The program manager wants to be emailed every six hours with a list of programmers who have consumed 5 or more Beers in a row, within the last 6 hours, without having a shot of vodka/whiskey, or a glass of water. The total number of beers that each programmer has consumed without switching to another drink at least once needs to be included in the report.

If at least one drink other than a beer is consumed before reaching 5 beers, then that programmer will not go on the list.

There are no upper or lower bounds on the number of drinks that a programmer can consume in a 6-hour period.

There are no requirements on the type or order of drinks that any programmer can consume.

The MySQL database has a table 'drinks' with:

  • drinks_id INT(11) PK NN AI
  • group_id INT(11) NN
  • programmer_id INT(11) NN
  • type_of_drink VARCHAR(25) NN
  • time_finished DATETIME NN

(type of drink should probably be in another table and the drink_type_id used, but I'm going for simplicity here)

The core of what I'm looking for is the maximum count value of the number of consecutive rows with type_of_drink = 'beer' for every group/programmer combination during a specified period of time. I've exhausted my sql skills trying to count the number of consecutive records which exist between two records with type_of_drink <> 'beer' and returning the maximum value for each group/programmer combination. I can't seem to get it right, and that may not be the way to look at this problem in the first place.

Thanks in advance. I'll be happy to provide any additional information or requirements if needed.

Was it helpful?

Solution

SELECT DISTINCT programmer_id 
FROM (
    SELECT
    programmer_id,
    @beercounter := IF(@prev_programmer != programmer_id OR type_of_drink != 'beer', 1, @beercounter + 1) AS how_many_beer_in_a_row,
    @prev_programmer := programmer_id
    FROM
    your_table y
    , (SELECT @beercounter:=1, @prev_programmer:=NULL) vars
    WHERE time_finished >= NOW() - INTERVAL 6 HOUR
    ORDER BY programmer_id, time_finished
) sq
WHERE how_many_beer_in_a_row >= 5
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top