2

我有 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 个表中的最晚日期结束。

4

2 回答 2

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 |

在这里拉小提琴。

(可选)在WITH ROLLUP之后添加GROUP BY以显示总数。

于 2013-11-09T04:17:16.213 回答
0

使用COUNTGROUP BY

    SELECT 
        `timestamp`
         COUNT( * ) as numEntries
    FROM
         tbl
    GROUP BY
        `timestamp`
于 2013-11-09T04:14:12.033 回答