嗨,我希望你们能提供帮助,我加入了几张桌子,以获得我需要的正确信息列表。现在我被困在最后一件事上了。 我需要找到一行和一列中结束日期/时间的小时数以及不同列中不同行的开始日期/时间。
-------------------------------------------------
ID Name Startdate EndDate
-------------------------------------------------
1 BILL 2017-10-10 09:00 2017-10-10 19:00
1 BILL 2017-10-11 09:00 2017-10-11 19:00
1 BILL 2017-10-15 09:00 2017-10-15 15:00
1 BILL 2017-10-22 09:00 2017-10-22 11:00
2 TOM 2017-10-10 09:00 2017-10-10 14:00
2 TOM 2017-10-12 09:00 2017-10-12 16:00
3 SAM 2017-10-13 09:00 2017-10-13 20:00
3 SAM 2017-10-14 09:00 2017-10-14 19:00
-------------------------------------------------
--------------------------------------------------------------------
ID Name Startdate EndDate Hours Diff
--------------------------------------------------------------------
1 BILL 2017-10-10 09:00 2017-10-10 19:00 NULL
1 BILL 2017-10-11 09:00 2017-10-11 19:00 14
1 BILL 2017-10-15 09:00 2017-10-15 15:00 86
1 BILL 2017-10-22 09:00 2017-10-22 11:00 162
2 TOM 2017-10-10 09:00 2017-10-10 14:00 NULL
2 TOM 2017-10-12 09:00 2017-10-12 16:00 43
3 SAM 2017-10-13 09:00 2017-10-13 20:00 NULL
3 SAM 2017-10-14 09:00 2017-10-14 19:00 13
--------------------------------------------------------------------

SELECT
a.ID
,b.FirstName
,b.LastName
,c.StartTime
,c.EndTime
from
table1 as a
inner join table2 as b on a.idnumber = b.idnumber
left join table3 as c on a.idnumber = c.idnumber
where
((Select Count(idnumber) as expr1
From table1 as ab
where idnumber = a.idnumber))<=1)
Order by a.idnumber
&#13;
在SQL中完成它会很好,但如果在表达式中使用SSRS更简单,而不是SQL,因为这会被放入一个非常棒的报告中。
任何帮助都会很棒,我确信它只是遇到问题很简单。 感谢。
答案 0 :(得分:0)
对于这个简单的案例,你可以使用:
select id, name, startdate, enddate,
DATEDIFF(hh, (
select MAX(enddate)
from Table1 as T2
where T1.id = T2.id
and T1.startdate > T2.enddate ), startdate)
as [Hours Diff]
from table1 as T1
order by id, startdate
这里有一个有效的例子:http://sqlfiddle.com/#!6/95827/8
答案 1 :(得分:0)
您想要按顺序比较的行吗? Row2 enddate vs Row1 startdate Row3 enddate vs Row2 startdate 等...
如果是这种情况,你可以使用&#34; lag&#34;函数将来自不同行的值引入正在比较的当前行。
我用Turophile的代码做了类似的事情:
select
id,
name,
startdate,
enddate,
datediff(hh,lag(startdate)over(partition by name order by startdate
asc),enddate)
from
table1 as T1
order by id, startdate
答案 2 :(得分:0)
使用LAG()
- 获取以前的记录数据和DATEDIFF
- 获取日期/小时差异
SELECT ID,Name ,Startdate,EndDate,
DATEDIFF(HOUR,
LAG(EndDate) OVER(PARTITION BY ID ORDER BY Startdate),
Startdate) AS Hours_Diff
FROM TABLE1
ORDER BY ID,Startdate
结果: -
ID Name Startdate EndDate Hours_Diff
1 BILL 2017-10-10 09:00 2017-10-10 19:00 NULL
1 BILL 2017-10-11 09:00 2017-10-11 19:00 14
1 BILL 2017-10-15 09:00 2017-10-15 15:00 86
1 BILL 2017-10-22 09:00 2017-10-22 11:00 162
2 TOM 2017-10-10 09:00 2017-10-10 14:00 NULL
2 TOM 2017-10-12 09:00 2017-10-12 16:00 43
3 SAM 2017-10-13 09:00 2017-10-13 20:00 NULL
3 SAM 2017-10-14 09:00 2017-10-14 19:00 13