Sql server 合并联接查询中的两行SQL数据

Sql server 合并联接查询中的两行SQL数据,sql-server,tsql,Sql Server,Tsql,我已经构建了以下查询,它成功地运行了我需要的报告。但是,punch_in和punch_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)

我已经构建了以下查询,它成功地运行了我需要的报告。但是,
punch_in
punch_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_in
punch_out
时间


我遗漏了什么?

您提供的信息很少,以下是我的尝试:

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

您能否提供最小的表定义和数据,以便有人能够重现您的问题。另外,你能减少你的查询吗?例如,为了解决你的问题,我们真的需要知道关于
getCleanHomeKeepTime
?你好,不知道这些表的结构就知道很复杂,但我认为你的错误在于连接,你有这个“on sl.id=sl2.id”,我想你想要这个“在sl1.clean\u home\u id=sl2.clean\u home\u id上“或者类似的。动机:一张桌子的清洁记录、家庭记录、状态记录是一个打孔,你有两次那个桌子。但在加入时,你是以相同的记录加入,而不是以退出的记录加入record@JoãoGonçalves谢谢,我会试试的。@DeanOC不是真的。是的,我认为函数是必要的,因为它是结果的一部分。样本数据最好作为+。请把你的问题包括进去。是的。。。我没有看到订单条款。。。我刚刚编辑了queryya,但是这种格式仍然会抱怨customer_name不是聚合函数的一部分。customer_name只是c.first_name的别名,因此查询应该可以正常工作:|