[英]SQL query to get fields from 2nd table based on input from 1st
我有 2 個表,table1 和 table2
表格1 -
錫 | 時間戳 |
---|---|
123 | 123456 |
表2 -
錫 | 時間戳 | 代碼 |
---|---|---|
456 | 123456 | xxxxx |
我想首先使用最大時間戳(紀元)從 table1 中獲取 sn,然后使用從 table1 返回的 sn 查詢表 2,並從 table2 中獲取具有最大時間戳的代碼。
我正在嘗試這個但遇到錯誤 -
select code from table2 where sn = (select sn, max(timestamp) from table1 GROUP BY sn)
我應該改用聯接嗎?
嘗試這個:
select DISTINCT code from table2
where sn = (select sn from table1 WHERE timestamp = (SELECT MAX(timestamp) FROM Table1));
您可以使用以下代碼執行此操作:
SELECT code
from table2 t
where sn = (SELECT sn
FROM table1 t1
INNER JOIN (SELECT MAX(timestamp) AS max_ts
FROM table1) d
ON t1.timestamp = d.max_ts
)
INNER JOIN (SELECT MAX(timestamp) AS max_ts
FROM table2) t2
ON t.timestamp= t2.max_ts;
但是,使用您提供的示例表將不會返回任何結果,因為在 table2 中找不到 sn 123
為了獲得“最新”值,我總是使用窗口函數。
為了保持一切干凈,我使用了兩個 CTE 來定義兩個數據集,但如果需要,您可以將所有內容放在一個查詢中。
WITH latestDataT1 AS (
SELECT
sn
,timestamp
FROM (
SELECT
sn
,timestamp
,ROW_NUMBER() OVER(ORDER BY timestamp DESC) as RowNo
FROM table1
)
WHERE
RowNo = 1
)
WITH latestDataT2 AS (
SELECT
sn
,timestamp
,code
FROM (
SELECT
sn
,timestamp
,code
,ROW_NUMBER() OVER(PARTITION sn BY ORDER BY timestamp DESC) as RowNo
FROM table2
)
WHERE
RowNo = 1
)
SELECT
*
FROM latestDataT1 AS t1
LEFT JOIN latestDataT2 AS t2
ON t1.sn = t2.sn
您可以嘗試以下腳本之一:
1) select code from table2 where (sn, timestamp) in (select sn, max(timestamp) from table1 GROUP BY sn);
2)
select A.code, B.maxtime
from table2 A,
(select sn, max(timestamp) as maxtime
from table1 GROUP BY sn) B
where A.sn = B.sn
and A.timestamp = B.maxtime;
謝謝
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.