Search code examples
mysqlsqlexcelcross-join

How do I cross join the date to a selection?


I need a query that will have the date, a user's name, and one of twelve operation_id's for that date. eg

operations
"id";"name";
"1";"LASER CUTTING"
"2";"DEBURR"
"3";"MACHINING"
"4";"BENDING"
"5";"PEM"
"6";"WELDING"
"7";"PAINT PREPARATION"
"8";"PAINTING"
"9";"SILKSCREEN PREPARATION"
"10";"SILKSCREEN"
"11";"ASSEMBLY - PACKAGING"
"12";"LASER PREP";

and a users table

bob
jimmeh
jimbo

I have a cross join between those tables to get something like this:

bob 1
bob 2
bob 3
bob 4
bob 5
bob 6
bob 7
bob 8
bob 9
bob 10
bob 11
bob 12
jimmeh 1
jimmeh 2
jimmeh 3
jimmeh 4
jimmeh 5
jimmeh 6
jimmeh 7
jimmeh 8
jimmeh 9
jimmeh 10
jimmeh 11
jimmeh 12
jimbo 1
jimbo 2
jimbo 3
jimbo 4
jimbo 5
jimbo 6
jimbo 7
jimbo 8
jimbo 9
jimbo 10
jimbo 11
jimbo 12

But I would also like to cross join every day between January 1st of 2011 and now so that I can use this query to give me a record for every person for every operation for every day so that I can put it in a pivot table and then use that to drive a report for each week for each user for each operation.

As of now I have a simple select userid from db.users join operations where departmentid = 8

I tried this:

select 
  userid, 
    first_name, 
    last_name,
    operations.id,
    operations.name
from 
  protocase.tblusers 
join
  operations
join
  select (BETWEEN "2011-01-01" and NOW())
where 
  departmentid = 8 and 
    protocase.tblusers.active = 1

Similar to how one would select (1,2,3) or something else that's not from a table, but I can't seem to figure out how I would select all the dates between January 1st and now. Is this even possible?


Solution

  • You could create a date table like this http://www.techrepublic.com/blog/datacenter/simplify-sql-server-2005-queries-with-a-dates-table/326

    Edit: Added stored procedure to generate dates:

    DROP PROCEDURE IF EXISTS datePopulate;
    DELIMITER $$
    CREATE PROCEDURE datePopulate( startDate datetime, numDays int)
    BEGIN
    
    declare currDate datetime default startDate;
    declare i int default 1;
    
    WHILE (i<=numDays) DO       
    
        INSERT INTO DateLookup(DateFull, fullYear, weekdayname) 
        VALUES(currDate, date_format(currDate, '%Y'), date_format(currDate, '%a'));
        SET i = i+1;
        SET currDate = DATE_ADD(currDate , INTERVAL 1 DAY);
    
    END WHILE;
    
    END $$
    DELIMITER ;
    

    Once procedure is created, it can be called like this:

    CALL datePopulate('2011-01-01', 30);
    

    This will populate the table with 30 days starting at 2011-01-01.

    I didn't add all the columns in the insert statement. Should be pretty straight forward to add though using information from here.