Click here to Skip to main content
15,894,540 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
How to get data from multiple tables with case on one table, I tried like below but getting error.

What I have tried:

SQL
select login.UserNname,LastLoggedInDetails.LoggedInIP,UserType.UserType,LastLoggedInDetails.LoggedInTime,
LastLoggedInDetails.LoggedOutTime,LastLoggedInDetails.LoggedInVersion,CompanyRegistered.Comp_Name,

case 

<pre>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
Posted
Updated 2-Mar-16 3:53am
Comments
CHill60 2-Mar-16 9:40am    
"but getting error" - what error?
ZurdoDev 2-Mar-16 9:53am    
Just fix the error. What's the issue?
ZurdoDev 2-Mar-16 9:54am    
By the way, your title is misleading. You say you want to join using a case statement. Your case statement is not in the join.

1 solution

The naming of the column duration has to come after the END of the CASE statement
SQL
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
 
Share this answer
 
Comments
Maciej Los 2-Mar-16 13:34pm    
Hawk eye, +5!
CHill60 2-Mar-16 16:22pm    
I haven't been "Hawkeye" for a while ... it was due ;-p Thank you

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900