SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 SQL Server 2012 Forums
 Transact-SQL (2012)
 group by question
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

nirnir
Starting Member

10 Posts

Posted - 10/14/2013 :  08:25:09  Show Profile  Reply with Quote
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
Flowing Fount of Yak Knowledge

3760 Posts

Posted - 10/14/2013 :  08:40:15  Show Profile  Reply with Quote

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
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

India
52325 Posts

Posted - 10/14/2013 :  09:01:52  Show Profile  Reply with Quote
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 - 10/16/2013 :  02:47:21  Show Profile  Reply with Quote
Thanks guys
Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.06 seconds. Powered By: Snitz Forums 2000