tags:

views:

56

answers:

2

I have a table with the only relevant column being completionDate, a number of seconds after the epoch that an item was marked complete. I would like to do a select statement to count the number of items complete, grouped by the week in which they were marked complete. So far, I've got something like this:

SELECT (completionDate-min)/(60*60*24*7)
FROM 
    (SELECT min(completionDate) AS min
     FROM TASK)
LEFT JOIN task;

Which returns these results:

0
2
2
2
3
3
3

Which means that 1 item was completed in the first week, and 3 items were completed in the third and 4th weeks.

I can deal with finding a better value for min programatically (specifically, the beginning of the week). What I really need is a way to group by the result and count the number of results. An ideal result would be:

0|1
2|3
3|3

My next step was to try this:

SELECT COUNT(idx)
FROM
    (SELECT ((completionDate-min)/(60*60*24*7)) AS idx
    FROM
         (SELECT min(completionDate) AS min
         FROM TASK)
    LEFT JOIN task)
GROUP BY idx;

Which gives results that look sort of kind of right, but wrong in a way I don't understand:

0
1
3
3

At this point, I'm just stuck. I admit my SQL is not that great, so any optimization on what I have would also be appreciated.

A: 

Figured it out. Had some null values. Added a WHERE completoinDate NOT NULL:

SELECT idx, COUNT(idx)
FROM
    (SELECT ((completionDate-min)/(60*60*24*7)) AS idx
    FROM
         (SELECT min(completionDate) AS min
         FROM TASK)
    LEFT JOIN task WHERE completionDate NOT NULL)
GROUP BY idx;

Please still let me know if it can be optimized in any way.

Ed Marty
+2  A: 
SELECT (completionDate - min) / (60*60*24*7) AS week,
       COUNT(*) AS count
FROM task, (SELECT MIN(completionDate) AS min FROM task)
GROUP BY week
HAVING completionDate NOT NULL;
Georg