mike smith
mike smith

Reputation: 53

show data by dates mysql

I have 3 mysql tables with data on the products with timestamp categorized by serial numbers.

i would like to show how many distinct serial number entries are in each table by date.

Table 1:

serial       timestamp

1               7/7/13
2               7/7/13
3               7/8/13
4               7/9/13
5               7/9/13
6               7/9/13

Table 2:

serial        timestamp
1               7/6/13
2               7/7/13
3               7/8/13
4               7/9/13

table 3:

serial        timestamp
1                7/9/13
2                7/10/13
3                7/10/13

output should be this:

date      table1      table2       table3
7/6/13      0           1            0
7/7/13      2           1            0
7/8/13      1           1            0
7/9/13      3           1            1
7/10/13     0           0            2
Total       6           4            3

looking for the most elegant way to do this and display this in html via PHP. need to start the output table with the earliest date in the 3 tables and end with the latest date in the 3 tables.

Upvotes: 2

Views: 80

Answers (2)

Mosty Mostacho
Mosty Mostacho

Reputation: 43434

You will have to first merge all the data into one derived table and then pivot that table:

SELECT timestamp,
  COUNT(CASE WHEN tableNumber = 1 THEN tableNumber END) table1Total,
  COUNT(CASE WHEN tableNumber = 2 THEN tableNumber END) table2Total,
  COUNT(CASE WHEN tableNumber = 3 THEN tableNumber END) table3Total
FROM (
  SELECT timestamp, 1 tableNumber FROM table1
  UNION ALL
  SELECT timestamp, 2 FROM table2
  UNION ALL
  SELECT timestamp, 3 FROM table3
) c
GROUP BY timestamp

Output:

|     TIMESTAMP | TABLE1TOTAL | TABLE2TOTAL | TABLE3TOTAL |
|---------------|-------------|-------------|-------------|
| July, 06 2013 |           0 |           1 |           0 |
| July, 07 2013 |           2 |           1 |           0 |
| July, 08 2013 |           1 |           1 |           0 |
| July, 09 2013 |           3 |           1 |           1 |
| July, 10 2013 |           0 |           0 |           2 |

Fiddle here.

Optionally add WITH ROLLUP after the GROUP BY to show the totals.

Upvotes: 1

willy
willy

Reputation: 1490

Use COUNT and GROUP BY

    SELECT 
        `timestamp`
         COUNT( * ) as numEntries
    FROM
         tbl
    GROUP BY
        `timestamp`

Upvotes: 0

Related Questions