Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Selecting row data as column in resultset 1

Status
Not open for further replies.

snitin78

Programmer
Mar 16, 2009
96
US
Hi Guys,

Due to time constraints I did very minimal search on the forums here, so I am sorry if this has been answered previously..I am just throwing it out there!

Here is what I need help with:

I have a users table and then a join table between users and some attributes (lets call this table user_attributes). Now I would like to select data from the users table with all columns from the users table along with the first attribute associated to the user as an additional column in the result.

Basically, if users X & Y have the following attributes:

User Attribute
X A
X B
X C
Y A1
Y B1
Y C1

then when I do select * from users where user= X what I would like to get is:

user_name user_something ..... attribute
X some abc ..... A
Y some abc ..... A1

That chosen attribute has to be the top 1 of the attributes associated with the user. What should I add in the select statement to get this result?

Any help on how to achieve this is greatly appreciated. Thanks in advance.
 
Just for information, the environment is MS SQL Server 2008 in compatibility mode.
 
Argh!!! This time crunch is taking the toll on me...

Please read my select statement as
Code:
select * from users where user in (X, Y)
 
Oops, I meant

select * from (Select U.*, row_number() over (order by Attribute) as rn from Users U) Ordered where rn = 1
 
HI Markos,

Thanks for the reply. The link looks promising :).

For your solution, I did not understand the over "(order by Attribute)" part. User and Attribute are 2 separate tables...can I still do what you have proposed.
 
Yes, you can still do the same, just join both tables as you do normally.

E.g.

select * from (select U.*, A.*, row_number() over (Partition by UserID order by Attributes) as rn from Users U inner join Attributes A on U.UserID = A.UserID) D where D.rn = 1
 
Hi,

How about...

Code:
select u.*,
(select top 1 att from [user_attribute] a where a.id = u.id) as attribute
from [user] u

Ryan
 
Cool! I achieved what I needed using CTEs and row_number as mentioned by Markos. :)

Thanks a ton for your responses guys.

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top