Question

I have a table in the following format.

FIELD           TYPE           DATA EXAMPLE
----------------------------------------------
id           |  int(11)     |  123
job          |  int(7)      |  456
date         |  datetime    |  0000-00-00 00:00:00
complete     |  tinyint(4)  |  0 or 1 

I need to write a query that will go though this large table and count how many records per project per day with with complete status 0 and complete status 1.

Because there might be multiple entries on the same day, I thought of first running one query and get unique dates:

SELECT DISTINCT DATE(date) AS dt
FROM mytable
ORDER BY DATE(date) ASC

and then run another query within and do the count

SELECT
    SUM(id) AS cnt,
    job,
    DATE(date)
FROM mytable
WHERE complete = 0
AND DATE(date) = '".$uniqueDate."'
GROUP BY job

But is is starting to get a bit convoluted because I'll also need to run a second similar query for complete = 1

There's gotta be a better way of doing this, hah?..

UPDATE:

The data looks somewhat like this:

is    job       date                   complete
-----------------------------------------------
234   324234    2011-06-17 06:59:24     0
235   324234    2011-06-17 08:09:22     1
235   544560    2011-06-18 02:51:12     0
244   677234    2012-07-17 11:12:14     1

Basically when the initial script will run it will collect the data and insert it into another table in the following format:

stat_jobID        (job ID from previous table)
stat_date         (date from previous table)
stat_complete     (count total)
stat_incomplete   (count total)
Was it helpful?

Solution

Just as complete to the GROUP BY criteria, so you get each count.

SELECT job,
       complete,
       DATE(date) AS report_date,
       COUNT(*)
FROM mytable
GROUP BY job, complete, report_date

You could also pivot it, so you get complete and incomplete on the same row:

SELECT job,
       SUM(complete >= 1) AS completed,
       SUM(complete = 0) AS not_completed,
       DATE(date) AS report_date
FROM mytable
GROUP BY job, report_date

SQLFIDDLE

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top