有两张表,table1 ,table2,
table1
id name
1101 北京-入库
1102 北京-出库
1103 北京-降雨
1104 北京-平均
2101 广州-入库
2102 广州-出库
2103 广州-降雨
2104 广州-平均
.......
table1中的id是传感器,传感器会每小时抓取数据入库
id time data
1101 8:00 20
1101 7:04 25
.....
1102 4:00 30我现在需要的数据是这样子,比如我想知道北京 当前时间最大的传感器 的数据
如
id name time data
1101 北京-入库 8:00(1101中时间最大) 20
1102 北京-出库 8:00(1102中时间最大) 40
.........
我写了一个这样的sql
select max(time),id from table2 where id in(
select id from table1 where name like '%北京%' and (
name like '%北京-出库%' or name like '%北京-出库%') ) group by id
这样只能得到
id max(time) 这两个字段,由于这两个字段都不是唯一,也就是说,table2中时间有很多相同的,id也有很多相同的
无法在外面嵌套select * from table2 where id in(。。)这样子来获得其他字段,
小弟sql很菜,求高手帮帮忙啊!
table1
id name
1101 北京-入库
1102 北京-出库
1103 北京-降雨
1104 北京-平均
2101 广州-入库
2102 广州-出库
2103 广州-降雨
2104 广州-平均
.......
table1中的id是传感器,传感器会每小时抓取数据入库
id time data
1101 8:00 20
1101 7:04 25
.....
1102 4:00 30我现在需要的数据是这样子,比如我想知道北京 当前时间最大的传感器 的数据
如
id name time data
1101 北京-入库 8:00(1101中时间最大) 20
1102 北京-出库 8:00(1102中时间最大) 40
.........
我写了一个这样的sql
select max(time),id from table2 where id in(
select id from table1 where name like '%北京%' and (
name like '%北京-出库%' or name like '%北京-出库%') ) group by id
这样只能得到
id max(time) 这两个字段,由于这两个字段都不是唯一,也就是说,table2中时间有很多相同的,id也有很多相同的
无法在外面嵌套select * from table2 where id in(。。)这样子来获得其他字段,
小弟sql很菜,求高手帮帮忙啊!
select *
from table2,
table1
where table2.id = table1.id
and table1.name like '%北京%'
and (table2.id,table2.time) in (select id,max(time) from table2 group by id);
SELECT t1.ID, t1.NAME, t2.TIME, t2.DATA
FROM table1 t1,
(SELECT ID, TIME, DATA
FROM (SELECT ID, TIME, DATA,
ROW_NUMBER () OVER (PARTITION BY ID ORDER BY TIME DESC)
rn
FROM table2)
WHERE rn = 1) t2
WHERE t2.ID = t1.ID AND t1.NAME LIKE '北京%'
select id from table1 where name like '%北京%' and (
name like '%北京-出库%' or name like '%北京-出库%') ) group by id
红字部分可以省略,当like时“%”表示0或者多个字符,
另外你table2中ID, TIME可以作为联合主键处理的
顺便顶2楼
select a.id , a.name ,b.time,b.date from table1 a,table2 b where a.id = b.id and time=(select max(time)from table2);
这样就可以了