如何从一张桌子上的多个表中获取数据,我尝试如下,但收到错误。
select login.UserNname,LastLoggedInDetails.LoggedInIP,UserType.UserType,LastLoggedInDetails.LoggedInTime,
LastLoggedInDetails.LoggedOutTime,LastLoggedInDetails.LoggedInVersion,CompanyRegistered.Comp_Name,
case
when LastLoggedInDetails.LoggedOutTime is not null then CONVERT(VARCHAR(100),DATEDIFF (hour,LastLoggedInDetails.LoggedInTime ,LastLoggedInDetails.LoggedOutTime ))+' Hours '+
CONVERT(VARCHAR(100),DATEDIFF (minute,LastLoggedInDetails.LoggedInTime ,LastLoggedInDetails.LoggedOutTime )%60) +' Minutes' as Duration
when LastLoggedInDetails.LoggedOutTime is null then 'Running...' as Duration
end
from LastLoggedInDetails
join login on LastLoggedInDetails.LastLoggedUserId = login.RegistrationId
join UserType on LastLoggedInDetails.LastLoggedUserTypeId = UserType.UserTypeId
join CompanyRegistered on LastLoggedInDetails.RegCompanyId = CompanyRegistered.Comp_Id
答案 0 :(得分:0)
以下是case
的代码,格式化为有用:
case when LastLoggedInDetails.LoggedOutTime is not null
then CONVERT(VARCHAR(100),
DATEDIFF(hour, LastLoggedInDetails.LoggedInTime, LastLoggedInDetails.LoggedOutTime)
) + ' Hours ' +
CONVERT(VARCHAR(100),
DATEDIFF(minute, LastLoggedInDetails.LoggedInTime,
LastLoggedInDetails.LoggedOutTime
)%60
) +' Minutes' as Duration
--------------------------------^
when LastLoggedInDetails.LoggedOutTime is null
then 'Running...' as Duration
end
格式化代码会使问题变得明显:case
是一个可以命名的表达式。每个then
的单个结果都没有命名。所以,试试这个:
(case when LastLoggedInDetails.LoggedOutTime is not null
then CONVERT(VARCHAR(100),
DATEDIFF(hour, LastLoggedInDetails.LoggedInTime, LastLoggedInDetails.LoggedOutTime)
) + ' Hours ' +
CONVERT(VARCHAR(100),
DATEDIFF(minute, LastLoggedInDetails.LoggedInTime,
LastLoggedInDetails.LoggedOutTime
)%60
) +' Minutes'
when LastLoggedInDetails.LoggedOutTime is null
then 'Running...'
end) as Duration
答案 1 :(得分:0)
select login.UserNname,LastLoggedInDetails.LoggedInIP,UserType.UserType,LastLoggedInDetails.LoggedInTime,
LastLoggedInDetails.LoggedOutTime,LastLoggedInDetails.LoggedInVersion,CompanyRegistered.Comp_Name,
case
when LastLoggedInDetails.LoggedOutTime is not null then CONVERT(VARCHAR(100),DATEDIFF (hour,LastLoggedInDetails.LoggedInTime ,LastLoggedInDetails.LoggedOutTime ))+' Hours '+
CONVERT(VARCHAR(100),DATEDIFF (minute,LastLoggedInDetails.LoggedInTime ,LastLoggedInDetails.LoggedOutTime )%60) +' Minutes'
when LastLoggedInDetails.LoggedOutTime is null then 'Running...'
end as Duration
from LastLoggedInDetails
join login on LastLoggedInDetails.LastLoggedUserId = login.RegistrationId
join UserType on LastLoggedInDetails.LastLoggedUserTypeId = UserType.UserTypeId
join CompanyRegistered on LastLoggedInDetails.RegCompanyId = CompanyRegistered.Comp_Id