Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Query issue

Author  Topic 

fjudzon
Starting Member

19 Posts

Posted - 2010-08-06 : 16:29:58
Hi, I have 3 tables
user, phone and UserXPhones
at UserXPhones table, I have a field phoneType.
A user could have N phones.
I need to get the Home Phone Type of a given user and if he doesnt have a Home Phone, get the Office Phone.

How could I do that?

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2010-08-06 : 16:43:15
Use a CASE statement for this.

CASE WHEN...THEN...ELSE...END

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page

fjudzon
Starting Member

19 Posts

Posted - 2010-08-06 : 16:48:56
But,if the user has 2 phone types , how could I get only the Home Phone Type?


quote:
Originally posted by tkizer

Use a CASE statement for this.

CASE WHEN...THEN...ELSE...END

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog

Go to Top of Page

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2010-08-06 : 16:56:11
Please post some sample data.

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page

fjudzon
Starting Member

19 Posts

Posted - 2010-08-06 : 17:01:18
User 1

Table: UserXPhones
User 1 | Phone 1 | Phone Type 1
User 1 | Phone 2 | Phone Type 5
User 1 | Phone 3 | Phone Type 7

I want to get the User data (besides the phone data) and the phone data for Phone Type = 5 . If there is no Phone Type =5 for him, get Phone Type =1. If no Phone Type = 1, dont return any phone data.

thanks!
Go to Top of Page

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2010-08-06 : 17:16:41
Try this:

SELECT *
FROM
(
SELECT UserId, PhoneNo, PhoneType, RN = ROW_NUMBER() OVER (PARTITION BY UserId ORDER BY UserId ASC, PhoneType DESC)
FROM UserXPhones
WHERE PhoneType IN (1, 5)
) t
WHERE RN = 1


Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page
   

- Advertisement -