如何在此联接中仅选择具有最大ID的SQL行?

时间:2019-05-08 16:00:19

标签: sql google-bigquery

我需要从此联接表中获取具有最大ID的记录,但是我只需要在该子查询中将第一行与主查询联接。如何限制子查询仅返回一行?以前,返回的tran_state MAX无法正常工作。

LEFT JOIN (
   SELECT
     tran_id
     , MAX(id) AS max_tran_id
     , MAX(DATETIME(created, 'America/New_York')) AS max_tran_created
     , tran_state
   FROM `prod.tran` 
   GROUP BY tran_id
   ) data ON t.id = data.tran_id

我试图像这样修改查询,但tran_state返回为空。

LEFT JOIN (
    SELECT 
    tran_state, 
    tran_id 
    FROM `prod.tran` WHERE ID IN ( 
    SELECT
    MAX(ID)
    FROM `prod.tran` trans 
    WHERE trans.tran_id = transaction_id)
    ) data ON t.id = data.tran_id

2 个答案:

答案 0 :(得分:1)

尝试此查询。

SELECT *
FROM `prod.tran`
WHERE id IN (
    SELECT MAX(id)
    FROM `prod.tran`
    GROUP BY tran_id
) a

答案 1 :(得分:1)

您可以使用窗口功能:

LEFT JOIN
(SELECT t.*,
        ROW_NUMBER() OVER (PARTITION BY t.tran_id ORDER BY t.id DESC) as seqnum
 FROM `prod.tran` t
) data
ON t.id = data.tran_id AND t.seqnum = 1