2

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 |
1
  • Add TOP(1) and ORDER BY properly Commented Mar 15, 2013 at 21:05

2 Answers 2

5

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
Sign up to request clarification or add additional context in comments.

5 Comments

I think it should be order by gs_id desc
@Kaf - The title says max of a sum though.
Right, wrong order column... But the title is Max of sum... Thanks!
@MartinSmith: not a big issue :D
Sorry I forgot to say that I need to be able to comment out my product_ID so I will have many product_id's with multiple D.Green_Sheet_ID's and I just need the max D.Green_Sheet_ID row.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.