从JOIN查询合并两行SQL数据

时间:2018-05-01 00:29:01

标签: sql-server tsql

我已经构建了以下查询,该查询成功运行了我需要的报告。但是,punch_inpunch_out列并非如我所愿。

SELECT c.first_name as customer_name, ch.id as clean_home_id, sl.modified_date as punch_in,sl2.modified_date as punch_out, e.first_name as employee_name, ch.employee_id,isnull(chlog.timespent, 0) AS timespent
FROM clean_home_status_log sl
INNER JOIN clean_home ch on sl.clean_home_id = ch.id
INNER JOIN customer c on ch.customer_id = c.id
INNER JOIN employee e on ch.employee_id = e.id
INNER JOIN clean_home_status_log sl2 on sl.id = sl2.id 
Outer APPLY GetCleanHomeKeeperTime(ch.id) chlog
WHERE (sl.new_status = 8 or sl.new_status = 9) and (c.id = 26749) and CONVERT(DATE,sl.modified_date) >= '2017-11-01' order by clean_home_id

产地:

Josh    82104   2017-11-01 14:16:21.947 2017-11-01 14:16:21.947 Lupe    1334    1.01
Josh    82104   2017-11-01 15:17:02.303 2017-11-01 15:17:02.303 Lupe    1334    1.01
Josh    82105   2017-11-02 14:23:35.803 2017-11-02 14:23:35.803 Lupe    1334    1
Josh    82105   2017-11-02 15:23:27.233 2017-11-02 15:23:27.233 Lupe    1334    1

正如您所看到的那样,重复每一行以显示第一行中的punch_in时间,并在每个结果的第二行中显示punch_out时间。我想要的是......

Josh    82104   2017-11-01 14:16:21.947 2017-11-01 15:17:02.303 Lupe    1334    1.01

显示同一行中的punch_inpunch_out时间

我缺少什么?

1 个答案:

答案 0 :(得分:-1)

根据您提供的少量信息,这是我的尝试:

SELECT 
    c.first_name as customer_name, 
    ch.id as clean_home_id,
    MIN(sl.modified_date) as punch_in,
    MAX(sl2.modified_date) as punch_out,
    e.first_name as employee_name,
    ch.employee_id,
    isnull(chlog.timespent, 0) AS timespent 
FROM clean_home_status_log sl 
INNER JOIN clean_home ch on sl.clean_home_id = ch.id 
INNER JOIN customer c on ch.customer_id = c.id 
INNER JOIN employee e on ch.employee_id = e.id 
INNER JOIN clean_home_status_log sl2 on sl.id = sl2.id 
Outer APPLY GetCleanHomeKeeperTime(ch.id) chlog 
WHERE (sl.new_status = 8 or sl.new_status = 9) and (c.id = 26749) and CONVERT(DATE,sl.modified_date) >= '2017-11-01' 
GROUP BY c.first_name, ch.id, e.first_name, ch.employee_id, isnull(chlog.timespent, 0)
order by clean_home_id