SQL Server选择最大总和

时间:2013-03-15 21:02:45

标签: sql sql-server-2008

当我运行此选择

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

我明白了......

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

我只想选择max(gs_is)的行,所以我只得到这个结果?

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

2 个答案:

答案 0 :(得分:5)

订购结果并执行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

答案 1 :(得分:1)

如果您要使用此查询来提取多个Product_ID,那么这只会返回相关结果。如果您的最终结果只是返回了一个项目,那么请使用Marcin的答案。

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