从具有多个条件的相同列查询日期

时间:2017-04-18 10:40:50

标签: mysql

我想查询客户端是否在1月到2月间由有线电视公司断开连接,以及他们是否在断开连接后7天再次连接。

我的表格是这样的:

+---------+----------+------------+------------+
| client  | ID_Order | Work_Order | Date_Order |
+---------+----------+------------+------------+
| Client1 | 123AB    | Disconnect | 20/01/2017 |
| Client1 | 234EA    | Connect    | 22/01/2017 |
| Client2 | 242FA    | Connect    | 30/01/2017 |
| Client3 | 244FE    | Disconnect | 30/01/2017 |
| Client2 | 301EA    | Disconnect | 10/02/2017 |
| Client4 | 355AD    | Disconnect | 20/02/2017 |
| Client4 | 368AD    | Connect    | 25/02/2017 |
| Client5 | 401AD    | Connect    | 05/03/2017 |
| Client6 | 440AD    | Disconnect | 15/03/2017 |
+---------+----------+------------+------------+

我想在这样的表中转换上一个表:每个客户端一行,连接顺序和断开顺序在2个不同的列中

+---------+-----------------+-------------+--------------+------------+
| client  | ID_Order_Discon | Date_Discon | ID_Order_Con |  Date_Con  |
+---------+-----------------+-------------+--------------+------------+
| Client1 | 123AB           | 20/01/2017  | 234EA        | 22/01/2017 |
| Client4 | 355AD           | 20/02/2017  | 368AD        | 25/02/2017 |
+---------+-----------------+-------------+--------------+------------+

我的问题: 1-如何在相同的列(Date_Order)中进行查询,以选择断开连接7天后连接的客户端。猜猜需要使用DATEDIFF()吗? 2-如何将同一客户的订单放在2个不同的列中?我猜我必须做一个IF()/ CASE()和一个join()?

1 个答案:

答案 0 :(得分:0)

要合并两个表,您可以使用:

select c1.client, cq.ID_Order ID_Order_Discon , c1.Date_Order as Date_discon, c2.ID_Order  ID_Order_Con, c2.Date_order Date_Con  
from table c1 join table c2 on t1.client = t2.client and t1.work-order = 'disconnect' and t2.work_order = 'Connect' 

对于第一个问题,您可以使用where DATEDIFF(c1.date_order,c2.dateOrder)>7