[英]SQL query to get fields from 2nd table based on input from 1st
I have 2 tables, table1 and table2我有 2 个表,table1 和 table2
table1 -表格1 -
sn锡 | timestamp时间戳 |
---|---|
123 123 | 123456 123456 |
table2 -表2 -
sn锡 | timestamp时间戳 | code代码 |
---|---|---|
456 456 | 123456 123456 | xxxxx xxxxx |
I want to first get the sn from table1 with max timestamp(epoch) and then query table 2 with the sn returned from table1 and get the code from table2 with the max timestamp.我想首先使用最大时间戳(纪元)从 table1 中获取 sn,然后使用从 table1 返回的 sn 查询表 2,并从 table2 中获取具有最大时间戳的代码。
I am trying this but getting errors -我正在尝试这个但遇到错误 -
select code from table2 where sn = (select sn, max(timestamp) from table1 GROUP BY sn)
Should i use joins instead?我应该改用联接吗?
Try this:尝试这个:
select DISTINCT code from table2
where sn = (select sn from table1 WHERE timestamp = (SELECT MAX(timestamp) FROM Table1));
You can do this using the following code:您可以使用以下代码执行此操作:
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;
However using the example tables you provided this will return no results, as the sn 123 isn't found in table2但是,使用您提供的示例表将不会返回任何结果,因为在 table2 中找不到 sn 123
To get the "latest" value I always use windowing functions.为了获得“最新”值,我总是使用窗口函数。
In order to keep everything clean, I've used two CTEs to define the two datasets but you can put everything in a single query if needed.为了保持一切干净,我使用了两个 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
Can you try one of these scripts:您可以尝试以下脚本之一:
1) select code from table2 where (sn, timestamp) in (select sn, max(timestamp) from table1 GROUP BY sn); 1) select code from table2 where (sn, timestamp) in (select sn, max(timestamp) from table1 GROUP BY sn);
2) 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;
Thank you谢谢
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.