简体   繁体   English

按日期显示数据mysql

[英]show data by dates mysql

I have 3 mysql tables with data on the products with timestamp categorized by serial numbers. 我有3个mysql表,其中按时间戳将产品数据按序列号分类。

i would like to show how many distinct serial number entries are in each table by date. 我想按日期显示每个表中有多少个不同的序列号条目。

Table 1: 表格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: 表2:

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

table 3: 表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. 寻找最优雅的方式来做到这一点,并通过PHP在html中显示。 need to start the output table with the earliest date in the 3 tables and end with the latest date in the 3 tables. 需要以3个表中最早的日期开始输出表,并以3个表中的最新日期结束输出表。

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. (可选)在GROUP BY之后添加WITH ROLLUP以显示总计。

Use COUNT and GROUP BY 使用COUNTGROUP BY

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM