我有3个mysql表,其中包含产品数据,时间戳按序列号分类。
我希望按日期显示每个表中有多少个不同的序列号条目。
表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
表2:
serial timestamp
1 7/6/13
2 7/7/13
3 7/8/13
4 7/9/13
表3:
serial timestamp
1 7/9/13
2 7/10/13
3 7/10/13
输出应该是这样的:
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
寻找最优雅的方式来实现这一点并通过PHP在html中显示。需要以3个表中最早的日期启动输出表,并以3个表中的最新日期结束。
答案 0 :(得分:1)
您必须先将所有数据合并到一个派生表中,然后转动该表:
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
输出:
| 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 |
小提琴here。
可选择在WITH ROLLUP
之后添加GROUP BY
以显示总计。
答案 1 :(得分:0)
使用COUNT
和GROUP BY
SELECT
`timestamp`
COUNT( * ) as numEntries
FROM
tbl
GROUP BY
`timestamp`