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 2012 Forums
 Transact-SQL (2012)
 group by question

Author  Topic 

nirnir
Starting Member

10 Posts

Posted - 2013-10-14 : 08:25:09
I have a table TableA with the fields :
recID : int
groupID : int
money :int

I use
select sum(money), min(money) , groupID from tableA group by groupID

I want to get also the recID of the record with min(money) ,How can I do that in the same sql statement ?

James K
Master Smack Fu Yak Hacker

3873 Posts

Posted - 2013-10-14 : 08:40:15
[code]
SELECT SumMoney, money AS MinMoney, groupid FROM
(
SELECT
SUM(money) OVER(PARTITION BY groupId) AS SumMoney,
money,
groupId,
ROW_NUMBER() OVER(PARTITION BY groupid ORDER BY money) AS RN
FROM
tableA
)s WHERE RN = 1[/code]
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2013-10-14 : 09:01:52
slight tweak to match Ops requirement


SELECT SumMoney, money AS MinMoney, groupid,recID
FROM
(
SELECT
SUM(money) OVER(PARTITION BY groupId) AS SumMoney,
money,
groupId,
ROW_NUMBER() OVER(PARTITION BY groupid ORDER BY money) AS RN,
recID
FROM
tableA
)s
WHERE RN = 1


------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page

nirnir
Starting Member

10 Posts

Posted - 2013-10-16 : 02:47:21
Thanks guys
Go to Top of Page
   

- Advertisement -