سؤال

I'm a SQL beginner. I have two SQLite tables: one with information about work times and one with time budget per weekday for specific time ranges. I wonder how I can select the correct budget for the day for any of the work time enterys.

Work_Times
+---------------------+---------------------+--------+
|        begin        |         end         | Note   |
+---------------------+---------------------+--------+
| 2011-08-02 00:00:00 | 2013-08-02 00:00:00 | Free   |
| 2011-10-15 06:00:00 | 2011-10-15 09:45:00 | Tour A |
| 2011-12-05 05:30:00 | 2011-03-05 10:00:00 | Tour B |
+---------------------+---------------------+--------+

Week_Budget
+------------+------------+------+------+------+------+------+------+------+-------+
| from       | to         | Mon  | Tue  | Wed  | Thu  | Fri  | Sat  | Sun  | sum   |
+------------+------------+------+------+------+------+------+------+------+-------+
| 01.08.2011 | 30.09.2011 | 3.80 | 3.80 | 3.85 | 3.80 | 0.00 | 0.00 | 0.00 | 15.25 |
| 01.10.2011 | 27.11.2011 | 4.18 | 4.18 | 4.25 | 4.18 | 0.00 | 0.00 | 0.00 | 16.79 |
| 28.11.2011 | 31.03.2012 | 3.25 | 3.25 | 3.25 | 3.25 | 3.00 | 0.00 | 0.00 | 16.00 |
+------------+------------+------+------+------+------+------+------+------+-------+

I think I can join the rows with …

WHERE Week_Buget.from => Work_Times.begin <= Week_Buget.to

… but I can't find a way to select the right column depenting on maybe the daynumber (%w).

هل كانت مفيدة؟

المحلول

OK, with the help of biziclops hint I found the CASE syntax and now got a solution:

SELECT wt.begin, wt.end, CASE
    WHEN strftime('%w', wt.begin)='1' THEN Mon
    WHEN strftime('%w', wt.begin)='2' THEN Tue
    WHEN strftime('%w', wt.begin)='3' THEN Wed
    WHEN strftime('%w', wt.begin)='4' THEN Thu
    WHEN strftime('%w', wt.begin)='5' THEN Fri
    WHEN strftime('%w', wt.begin)='6' THEN Sat
    WHEN strftime('%w', wt.begin)='0' THEN Sun END
    AS daybudget
FROM Week_Budget AS wb, Work_Times AS wt 
WHERE t.begin BETWEEN wb.from AND wb.to;

I got two further questions:

  1. Is there a smarter way to do this?
  2. What is the better way to get this done? The solution above or a query with an INNER JOIN like the following:

Version 2:

SELECT wt.begin, wt.end, CASE
    WHEN strftime('%w', wt.begin)='1' THEN Mon
    WHEN strftime('%w', wt.begin)='2' THEN Tue
    WHEN strftime('%w', wt.begin)='3' THEN Wed
    WHEN strftime('%w', wt.begin)='4' THEN Thu
    WHEN strftime('%w', wt.begin)='5' THEN Fri
    WHEN strftime('%w', wt.begin)='6' THEN Sat
    WHEN strftime('%w', wt.begin)='0' THEN Sun END
    AS daybudget
FROM Week_Budget AS wb
INNER JOIN Work_Times AS wt 
    ON t.begin BETWEEN wb.from AND wb.to;
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top