Select Id,
Name,
SUM(Price) As Price,
GroupId,
GroupName
(
Select Id,
Name,
SUM(Price) As Price,
GroupId,
GroupName,
Key,
Row_Number() OVER (PARTITION BY Id, GroupId ORDER BY Key) As rna
From #tmpTable
Group BY Id, Name, Price, GroupId, GroupName, Key
) As A
Where rna = 1
Group BY Id, Name, Price, GroupId, GroupName
How to group rows based on Min value of the column in SQL Server 2008
質問
I am looking for a way to group rows based on the minimum value of a column. Below is the scenario.. Any help would be appreciated.
For eg:
My Query:
Select Id, Name, SUM(Price) As Price, GroupId, GroupName, Key From #tmpTable Group BY Id, Name, Price, GroupId, GroupName, Key
I'm trying to use the Row_Number() as described in this post but having issues to get the SUM(price) of all similar GroupIds and Ids
My output is: 1 Test 300 3 G3
Vs
Expected output: 1 Test 600 3 G3
Thanks in advance!
Below is the query to resolve the issue I had. I'm still using Row_Number() and then rolling up Price to get the SUM. (nesting queries)
ANSWER Final Qry:
Select Id,
Name,
SUM(Price) As Price,
GroupId,
GroupName
(
Select Id,
Name,
SUM(Price) As Price,
GroupId,
GroupName,
Key,
Row_Number() OVER (PARTITION BY Id, GroupId ORDER BY Key) As rna
From #tmpTable
Group BY Id, Name, Price, GroupId, GroupName, Key
) As A
Where rna = 1
Group BY Id, Name, Price, GroupId, GroupName
解決
所属していません StackOverflow