Frage

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:

enter image description here

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
War es hilfreich?

Lösung

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
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top