Click here to Skip to main content
15,891,864 members
Please Sign up or sign in to vote.
1.42/5 (4 votes)
GroupId GeneralId values
3 11111 1.1
3 22222 2.2
3 33333 3.3
3 44444 4.4
2 55555 5.5
2 66666 6.6
2 77777 1.1
2 88888 2.3
1 11111 3.4
1 99999 4.3
1 22222 3.2
1 33333 2.2

Here GroupId always have latest updates of GeneralId.
I want unique row values of GeneralId.

Expected output is
GroupId GeneralId values
3 11111 1.1
3 22222 2.2
3 33333 3.3
3 44444 4.4
2 55555 5.5
2 66666 6.6
2 77777 1.1
2 88888 2.3
1 99999 4.3

From GroupId "1" ,GeneralId values "11111,22222,3333" should not repeat.

From below query

"SELECT GeneralId,MAX(GroupId) as 'General ID' FROM tbl GROUP BY GeneralId"

I got below output
GroupId GeneralId
3 11111
3 22222
3 33333
3 44444
2 55555
2 66666
2 77777
2 88888
1 99999

But please tell me how to get all GroupId,GeneralId with values.
Posted
Updated 11-Sep-14 3:44am
v4
Comments
Thanks7872 11-Sep-14 9:41am    
Dont repost questions. Its not allowed. Follow original thread only.

http://www.codeproject.com/Questions/817590/I-need-a-sql-select-query-to-retreive-data-with-be?arn=0
kalaivanan from Bangalore, India 11-Sep-14 9:45am    
it is not repost,it is having different scenario and my expected output is defferent.
Thanks7872 11-Sep-14 9:47am    
If you change number of rows that doesn't change the scenario.
_Asif_ 11-Sep-14 9:51am    
He is right, its a different scenario
kalaivanan from Bangalore, India 11-Sep-14 9:50am    
EXPECTED OUTPUT IS DIFFERENT, only thing is i used same table

1 solution

Try this

declare @TBL TABLE
(
  GROUPID INT,
  GENERALID VARCHAR(10),
  [VALUES] DECIMAL(10, 2)
);

INSERT INTO @TBL(GROUPID, GENERALID, [VALUES])
SELECT 3,'11111',1.1
UNION ALL SELECT 3,'22222',2.2
UNION ALL SELECT 3,'33333',3.3
UNION ALL SELECT 3,'44444', 4.4
UNION ALL SELECT 2,'55555', 5.5
UNION ALL SELECT 2,'66666', 6.6
UNION ALL SELECT 2,'77777', 1.1
UNION ALL SELECT 2,'88888', 2.3
UNION ALL SELECT 1,'11111',3.4
UNION ALL SELECT 1,'99999',4.3
UNION ALL SELECT 1,'22222',3.2
UNION ALL SELECT 1,'33333',2.2;

SELECT T.*
FROM
(
SELECT GENERALID, MAX(GROUPID) GROUP_ID
FROM @TBL
GROUP BY GENERALID
) A INNER JOIN @TBL T ON A.GENERALID = T.GENERALID AND A.GROUP_ID = T.GROUPID
Order by 1 desc, 2 
 
Share this answer
 
Comments
kalaivanan from Bangalore, India 11-Sep-14 10:10am    
Thanks, it worked for me.

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