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)
 group by?

Author  Topic 

rosenrosen
Starting Member

3 Posts

Posted - 2008-09-24 : 16:33:29
Lets say I have 3 columns A,B,C I want to return the data from each column but I only want to see 1 result per A.

| A | B | C |
----------------------
dog run fast
cat eat food
dog chase car
rat eat cheese

In this example, I want a select statement that returns 3 rows. I can take either "dog" row (but not both, that's my point). "distinct" and "group by" don't seem to be the answer but I'm probably missing something. thanks

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2008-09-24 : 16:40:45
SELECT dt.A, dt.B, t.C
FROM YourTable t
INNER JOIN (SELECT A, MAX(B) FROM YourTable GROUP BY A) dt
ON t.A = dt.A AND t.B = dt.B

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

Subscribe to my blog
Go to Top of Page

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2008-09-24 : 16:41:04
select top 3 a, b, c
from (
SELECT a, b, c, row_number() over (partition by a order by newid()) AS recid from table1
) AS d
where recid = 1


E 12°55'05.63"
N 56°04'39.26"
Go to Top of Page
   

- Advertisement -