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)
 grouping

Author  Topic 

sqlclarify
Yak Posting Veteran

56 Posts

Posted - 2009-02-07 : 22:46:35
I know I asked this question before but I can't find it.. and I have this problem again.. Lets say I have

SELECT
COLA,
COLB,
COLC,
COLQ,
FROM xyz....

I need to group by only COLA AND COL B. But according to the syntax I have to list all the columns. But if I do that it changes the meaning of the grouping. How do I avoid that? How do I get by this problem?

Thank you.

sodeep
Master Smack Fu Yak Hacker

7174 Posts

Posted - 2009-02-07 : 22:57:01
Provide sample data and expected output. What about other columns? How do you wanna return?
Go to Top of Page

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2009-02-08 : 00:57:29
Which values for ColC and ColQ do you want to return if there are duplicate records over ColA and ColB?



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

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2009-02-08 : 01:17:13
quote:
Originally posted by sqlclarify

I know I asked this question before but I can't find it.. and I have this problem again.. Lets say I have

SELECT
COLA,
COLB,
COLC,
COLQ,
FROM xyz....

I need to group by only COLA AND COL B. But according to the syntax I have to list all the columns. But if I do that it changes the meaning of the grouping. How do I avoid that? How do I get by this problem?

Thank you.


Yup. As you told when you group by COLA & COLB you can obviously bring only single set of values for other columns along with it. which value will you be interested in? first,last or random?

1.SELECT COLA,COLB,....
FROM
(
SELECT ROW_NUMBER() OVER (PARTITION BY COLA,COL B ORDER BY IDCol) AS Seq,
COLA,
COLB,
COLC,
COLQ,
FROM xyz....
)t
WHERE Seq=1

2.SELECT COLA,COLB,....
FROM
(
SELECT ROW_NUMBER() OVER (PARTITION BY COLA,COL B ORDER BY IDCol DESC) AS Seq,
COLA,
COLB,
COLC,
COLQ,
FROM xyz....
)t
WHERE Seq=1

3.SELECT COLA,COLB,....
FROM
(
SELECT ROW_NUMBER() OVER (PARTITION BY COLA,COL B ORDER BY NEWID()) AS Seq,
COLA,
COLB,
COLC,
COLQ,
FROM xyz....
)t
WHERE Seq=1


IDCol is unique valued column in your table
Go to Top of Page
   

- Advertisement -