开发者

SQLite expression to count rows grouped by week

开发者 https://www.devze.com 2022-12-09 18:00 出处:网络
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 ite

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 dea开发者_如何学编程l 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.


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;


Source of data:

SELECT strftime('%Y%W', date_col) AS w, other_data FROM my_table GROUP BY w

See http://sqlite.org/lang_datefunc.html for usage. That doc also
includes some caveats related to precision and locale, etc.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消