SQL选择具有最近日期的行

时间:2015-04-15 14:25:04

标签: sql sql-server-2008

我有两张桌子。

  • 采购订单(PURCHASE_ORDER)
  • 采购订单行(PURC_ORDER_LINE)

我需要特定部分的价格和货币,我还需要将返回的行作为数据库中的最新记录。

我认为,因为我想要最新的记录,我需要选择最大(日期)唯一的问题是,因为我需要'组,我的结果被分组并且它没有只需返回包含最新日期及其价格和货币的单行。

   SELECT MAX(PURC_ORDER_LINE.LAST_RECEIVED_DATE) AS 'Latest Order', 
   UNIT_PRICE, 
   PURCHASE_ORDER.CURRENCY_ID
   FROM PURC_ORDER_LINE
   LEFT JOIN PURCHASE_ORDER
   ON PURC_ORDER_LINE.PURC_ORDER_ID = PURCHASE_ORDER.ID
   WHERE PART_ID = 'some part'
   GROUP BY UNIT_PRICE, PURCHASE_ORDER.CURRENCY_ID

结果:

Latest Order UNIT_PRICE     CURRENCY_ID
2015-01-20      20              CHF
2015-04-06      30              CHF
2012-02-23      40              USD
2012-02-17      50              USD
2011-12-08      20              USD

我想要的是什么

UNIT_PRICE    CURRENCY_ID
30              CHF

5 个答案:

答案 0 :(得分:1)

也许是这样的: (另见https://msdn.microsoft.com/ru-ru/library/ms189463.aspx

   SELECT TOP(1) PURC_ORDER_LINE.LAST_RECEIVED_DATE, 
   UNIT_PRICE, 
   PURCHASE_ORDER.CURRENCY_ID
   FROM PURC_ORDER_LINE
   LEFT JOIN PURCHASE_ORDER
   ON PURC_ORDER_LINE.PURC_ORDER_ID = PURCHASE_ORDER.ID
   WHERE PART_ID = 'some part'
   ORDER BY PURC_ORDER_LINE.LAST_RECEIVED_DATE DESC

答案 1 :(得分:1)

为什么在只需要TOP 1和ORDER BY时使用GROUP BY?

SELECT TOP 1 LAST_RECEIVED_DATE, 
             UNIT_PRICE, 
             CURRENCY_ID
FROM PURC_ORDER_LINE
LEFT JOIN PURCHASE_ORDER ON(PURC_ORDER_LINE.PURC_ORDER_ID = PURCHASE_ORDER.ID)
WHERE PART_ID = 'some part'
ORDER BY LAST_RECEIVED_DATE DESC

答案 2 :(得分:0)

在这些情况下,我将从group by获取结果集,然后将其与查询结果集连接:

e.g。

SELECT * FROM (SELECT PURC_ORDER_LINE.PURC_ORDER_ID, MAX(PURC_ORDER_LINE.LAST_RECEIVED_DATE) LRDate
FROM PURC_ORDER_LINE
GROUP BY PURC_ORDER_LINE.PURC_ORDER_ID) Q
JOIN ..... ON condition

答案 3 :(得分:0)

SELECT
    p1.LAST_RECEIVED_DATE,
    UNIT_PRICE,
    po.CURRENCY_ID
FROM PURC_ORDER_LINE p1
INNER JOIN (
    SELECT PURC_ORDER_ID,MAX(LAST_RECEIVED_DATE) [MaxReceivedDate]
    FROM PURC_ORDER_LINE
    GROUP BY PURC_ORDER_ID
) MaxPur ON MaxPur.[MaxReceivedDate]=p1.LAST_RECEIVED_DATE AND p1.PURC_ORDER_ID=MaxPur.PURC_ORDER_ID
LEFT JOIN PURCHASE_ORDER po ON p1.PURC_ORDER_ID = po.ID
WHERE PART_ID = 'some part'
GROUP BY UNIT_PRICE, po.CURRENCY_ID

答案 4 :(得分:0)

;WITH CTE AS 
( SELECT PURC_ORDER_LINE.LAST_RECEIVED_DATE AS [Latest Order]
      ,UNIT_PRICE
      ,PURCHASE_ORDER.CURRENCY_ID
      ,ROW_NUMBER() OVER (PARTITION BY PURCHASE_ORDER.CURRENCY_ID 
                 ORDER BY PURC_ORDER_LINE.LAST_RECEIVED_DATE DESC) rn 
FROM PURC_ORDER_LINE
LEFT JOIN PURCHASE_ORDER
ON PURC_ORDER_LINE.PURC_ORDER_ID = PURCHASE_ORDER.ID
WHERE PART_ID = 'some part'
)
SELECT [Latest Order]
       ,UNIT_PRICE
       ,CURRENCY_ID
FROM CTE 
WHERE rn = 1