如何从此表中选择日期“span”?

时间:2017-04-17 07:06:12

标签: php mysql

我的SELECT结果包含带日期的列。这是结果中的一些数据:

ID   Name    status         start_date      end_date
A1   John    Planning       2017-03-03      2017-03-05
A1   John    Realizing      2017-03-05      2017-04-05
A1   John    Finishing      2017-04-05      2017-04-15
A1   John    Launching      2017-04-15      2017-04-16
A2   Lisa    Planning       2017-03-09      2017-03-13
A2   Lisa    Realizing      2017-03-13         NULL

我想知道planning -> Realizing -> Finishing -> Launching每个ID的进度状态。

我已经使用过这个查询,但我不知道它是否足够可靠和快速。真实的表包含数千个值。

SELECT x.id, x.name, CONCAT_WS(' to ', MIN(x.start_date), MAX(x.end_date)) AS progress FROM (SELECT * FROM team_project WHERE ID = 'A1')x

预期产出:

Name             Progress               total
John     2017-03-03 to 2017-04-16      44 days
Lisa     2017-03-09 to NOW               -

2 个答案:

答案 0 :(得分:0)

我认为group by你可以喜欢这个

SELECT id, name, CONCAT_WS(' to ', MIN(start_date), MAX(end_date)) AS progress 
FROM team_project group by ID 

答案 1 :(得分:0)

以下是没有 GROUP BY

的查询
SELECT
    tp1.`name`,
    CONCAT(tp1.start_date, ' to ',
        IF(tp2.end_date IS NULL, 'NOW', tp2.end_date)) AS Progress,
    DATEDIFF(IF(tp2.end_date IS NULL, NOW(), tp2.end_date),tp1.start_date) AS total
FROM team_project tp1
LEFT JOIN team_project tp2 ON tp1.id = tp2.id AND tp2.status 'Realizing'
WHERE tp1.status ='Planning';