简体   繁体   English

应该如何编写将多行合并为单行的 MySQL 语句?

[英]Should how compose MySQL statement for combining multiple rows to single row?

I have multiple rows in MySQL table the follow:我在 MySQL 表中有多行,如下所示:

| time       | status | count  | size   |
+------------+--------+--------+--------+
| 2017/01/22 |     -1 | 111111 | NULL   | 
| 2017/01/22 |      0 | 555555 | NULL   |
| 2017/01/22 |      1 | 333333 | 123456 |
| 2017/01/21 |      0 | 666666 | NULL   |
| 2017/01/21 |      1 | 444444 | 234567 |

Now I want to get the follow content:现在我想获得以下内容:

| time       | total  | success | failed | buffer |
+------------+--------+---------+--------+--------+
| 2017/01/22 | 555555 |  333333 | 111111 | 123456 |
| 2017/01/21 | 666666 |  444444 |      0 | 234567 |

I use time as id , total is count when status=0 , success is count when status=1 , failed is count when status=-1 , buffer is size when status=1 .我用time作为idtotalcountstatus=0successcountstatus=1failedcountstatus=-1buffersizestatus=1

So should I how write MySQL statement?那么我应该如何写MySQL语句呢?

You could use a self join您可以使用自连接

select a.time, a.count as totale, b.count  as success, c.count as failed, b.size as buffer 
from my_table as a 
left join my_table as  b on a.time = b.time and b.status = 1
left join my_table as  c on a.time = c.time and b.status = -1
where a.status = 0

You need to use sub-queries in order to get the data on the same line.您需要使用子查询来获取同一行上的数据。 Each sub-query searches for a specific type of data then an outer query joins the data together based on their times.每个子查询搜索特定类型的数据,然后外部查询根据它们的时间将数据连接在一起。 This should do what you are looking for:这应该做你正在寻找的:

SELECT success.time, success.count AS success, failed.count AS failed, buffered.count AS buffered
FROM (
(SELECT `count`, `time`
FROM tbl
WHERE `status` = 0) AS success
INNER JOIN 
    (SELECT `count` `time`
    FROM tbl
    WHERE `status` = 1) AS failed ON failed.time = success.time
INNER JOIN 
    (SELECT `count` `time`
    FROM tbl
    WHERE `status` = -1) AS buffered ON buffered.time = success.time
)

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

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