user2175554
user2175554

Reputation: 23

SQL Server Select Max of a Sum

When I run this select

SELECT      
     D.Product_ID p_id
    ,D.Green_Sheet_ID gs_id
    ,SUM (P.prepress_amt) amt

   FROM  GS_Prepress AS P INNER JOIN
                      GS_Data AS D ON P.green_sheet_id = D.Green_Sheet_ID

   WHERE 
    Product_ID ='194456'  
   GROUP BY D.Product_ID, D.Green_Sheet_ID

I get this...

|p_id   | gs_id |amt      |
|-------|-------|---------|
|194456 | 5721  |33524.00 |
|194456 | 7484  |47524.00 |

I only want to select the row with the max(gs_is), so I only get this result?

|p_id   | gs_id |amt      |
|-------|-------|---------|
|194456 | 7484  |47524.00 |

Upvotes: 2

Views: 5937

Answers (2)

MarcinJuraszek
MarcinJuraszek

Reputation: 125620

Order the results and take TOP(1):

SELECT TOP(1)
    D.Product_ID p_id,
    D.Green_Sheet_ID gs_id,
    SUM (P.prepress_amt) amt
FROM
    GS_Prepress AS P
INNER JOIN
    GS_Data AS D ON P.green_sheet_id = D.Green_Sheet_ID
WHERE 
    Product_ID ='194456'  
GROUP BY
    D.Product_ID, D.Green_Sheet_ID
ORDER BY
    gs_id DESC

Upvotes: 5

Matt Busche
Matt Busche

Reputation: 14333

If you're going to use this query to ever pull more than one Product_ID then this will only return the relevant results. If your end result is only to have one item returned then use Marcin's answer.

SELECT D.Product_ID p_id
, D.Green_Sheet_ID gs_id
,SUM (P.prepress_amt) amt
FROM  GS_Prepress AS P 
   INNER JOIN GS_Data AS D ON P.green_sheet_id = D.Green_Sheet_ID
   INNER JOIN (SELECT MAX(Green_Sheet_ID) AS gs_ID
               FROM GS_Date
               GROUP BY Product_ID) G ON G.Gs_ID = D.Green_Sheet_ID

WHERE Product_ID ='194456'  
GROUP BY D.Product_ID, D.Green_Sheet_ID

Upvotes: 1

Related Questions