2

当我运行这个选择

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 |
4

2 回答 2

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
于 2013-03-15T21:04:39.690 回答
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
于 2013-03-15T21:06:48.220 回答