根据条件将2行合并为1行

时间:2019-01-15 06:09:44

标签: mysql

我在MySQL中有这样的表

表1

| ID   | Name        | Time                  | Status    |
----------------------------------------------------------
| 1    | John        | 2018-12-17 08:14:17   | In        |
| 1    | John        | 2018-12-17 17:14:18   | Out       |
| 1    | John        | 2018-12-19 08:14:19   | In        |
| 1    | John        | 2018-12-19 17:14:39   | Out       |
| 2    | Sarah       | 2018-12-17 08:03:29   | In        |
| 2    | Sarah       | 2018-12-17 17:24:15   | Out       |
| 2    | Sarah       | 2018-12-18 08:04:11   | In        |
| 2    | Sarah       | 2018-12-18 17:05:49   | Out       |

表2

| ID   | Name        | 
----------------------
| 1    | John        |
| 2    | Sarah       |

我想得到这个结果

| ID   | Name        | In                    | Out                   |
----------------------------------------------------------------------
| 1    | John        | 2018-12-17 08:14:17   | 2018-12-17 17:14:18   |
| 1    | John        | 2018-12-19 08:14:19   | 2018-12-19 17:14:39   |
| 2    | Sarah       | 2018-12-17 08:03:29   | 2018-12-17 17:24:15   |
| 2    | Sarah       | 2018-12-18 08:04:11   | 2018-12-18 17:05:49   |

我尝试使用此代码

SELECT 
t2.`ID`,
t2.`Name`,
MAX(CASE WHEN t1.`Status` = 'In' THEN t1.`Time` END) In,
MAX(CASE WHEN t1.`Status` = 'Out' THEN t1.`Time` END) Out
FROM table2 t2
LEFT JOIN table1 t1
ON t1.`ID` = t2.`ID`
GROUP BY t2.`Name`

我该如何实现?

2 个答案:

答案 0 :(得分:0)

您可以尝试以下操作-使用添加date(Time) in group by clause

SELECT 
t2.`ID`,
t2.`Name`,
MAX(CASE WHEN t1.`Status` = 'In' THEN t1.`Time` END) In,
MAX(CASE WHEN t1.`Status` = 'Out' THEN t1.`Time` END) Out
FROM table2 t2
LEFT JOIN table1 t1
ON t1.`ID` = t2.`ID`
GROUP BY t2.`Name`,date(Time)

答案 1 :(得分:0)

您当前的查询存在一些问题。首先,您将保留字用作列别名,而不会在引号中转义它们。其次,您还需要按DATE(t1.time)进行分组,以避免出现full_group_by问题。最后,您需要按SELECT t2.`ID`, t2.`Name`, MAX(CASE WHEN t1.`Status` = 'In' THEN t1.`Time` END) AS `In`, MAX(CASE WHEN t1.`Status` = 'Out' THEN t1.`Time` END) AS `Out` FROM table2 t2 LEFT JOIN table1 t1 ON t1.`ID` = t2.`ID` GROUP BY t2.ID, t2.`Name`,DATE(t1.time) 分组才能每天获取In / Out时间。试试这个:

ID  Name    In                  Out
1   John    2018-12-17 08:14:17 2018-12-17 17:14:18
1   John    2018-12-19 08:14:19 2018-12-19 17:14:39
2   Sarah   2018-12-17 08:03:29 2018-12-17 17:24:15
2   Sarah   2018-12-18 08:04:11 2018-12-18 17:05:49

输出:

public class City {
    private String name;
    private String state;
    private String country;
    private boolean capital;
    private long population;
    private List<String> regions;

    public City() {}

    public City(String name, String state, String country, boolean capital, long population, List<String> regions) {

    // getters/setters
}

Demo on dbfiddle