将mysql行转换为列

时间:2018-12-10 11:09:16

标签: javascript php database mysqli

你能帮我吗?

需要将行值转换为按日期分组的列

select DATE(TimeStamp) as date ,Status ,count(Status) as value from  abc where (TIMESTAMP BETWEEN '2017-01-00 00:00:00' and '2018-10-09 23:59:59') AND  Name='xyz' GROUP BY DATE(TimeStamp),Status limit 15;

输出

+------------+--------------+-------+
| date       | Status       | value |
+------------+--------------+-------+
| 2017-08-09 | running      |   193 |
| 2017-08-09 | stop         |   726 |
| 2017-08-09 | UnknownError |   814 |
| 2017-08-10 | running      |   417 |
| 2017-08-10 | stop         |  1584 |
| 2017-08-10 | UnknownError |  1776 |
| 2017-08-11 | running      |   419 |
| 2017-08-11 | stop         |  1584 |
| 2017-08-11 | UnknownError |  1776 |
| 2017-08-12 | running      |   418 |
| 2017-08-12 | stop         |  1584 |
| 2017-08-12 | UnknownError |  1776 |
| 2017-08-13 | running      |   420 |
| 2017-08-13 | stop         |  1584 |
| 2017-08-13 | UnknownError |  1776 |
+------------+--------------+-------+

预期输出:

+------------+--------------+---------+--------------+
| date       | stop         | running |UnknownError  |
+------------+--------------+---------+--------------+
| 2017-08-09 |  726         |   193   |814           |
+------------+--------------+---------+--------------+

2 个答案:

答案 0 :(得分:0)

答案 1 :(得分:-1)

select Date(Timestamp),round(AVG(case when Status='stop' then stop else 0 end),2) 'stop',round(AVG(case when NodeName='running' then running else 0 end),2) 'running' from abc  where (Timestamp >= '2018-08-09' AND Timestamp<='2018-08-13') group by Date(Timestamp);