在sqlserver中,我要的意思呢用下面一条条单独的sql语句表达
select top 1 * from 同一个表 where 条件1 order by 时间字段 desc
.....
.....
select top 1 * from 同一个表 where 条件i order by 时间字段 desc
条件是个记录集,现在我怎么把他们合并写成一条?
...全文
13614打赏收藏
请问怎样写这样的sql。。。
在sqlserver中,我要的意思呢用下面一条条单独的sql语句表达 select top 1 * from 同一个表 where 条件1 order by 时间字段 desc ..... ..... select top 1 * from 同一个表 where 条件i order by 时间字段 desc 条件是个记录集,现在我怎么把他们合并写成一条?
select top 1 * from table1 where 字段 in (变量1,变量2,变量3) order by KEY
union
select top 1 * from table2 where 字段 in (变量1,变量2,变量3) order by KEY
union
select top 1 * from table3 where 字段 in (变量1,变量2,变量3) order by KEY
...
select x.水库, y.报汛站, z.降雨量
from 表1 x, 表2 y, 表3 z
where z.报汛站=y.报汛站
and y.水库=x.水库
and x.水库 in (一个数组变量)
and z.时间字段 in (Select max(时间字段)
from 表3
where 报汛站 = z.报汛站);
测试通过.
1.create table table db_name (字段与各报讯站设表结构相同)
2.insert into db_name
select top 1 * from 同一个表 where 条件1 order by 时间字段 desc
3.insert into db_name
select top 1 * from 同一个表 where 条件i order by 时间字段 desc
总之, 建一临时表db_name, 把各报讯站最新一条信息分别插入到db_name,使用时直接查临时表.
select top 1 * from table1 where 条件1 order by KEY
union
select top 1 * from table1 where 条件2 order by KEY
union
select top 1 * from table1 where 条件3 order by KEY
...
我在详细说一下:
表1:水库;表2:报汛站,表3:各报汛站的降雨量信息
关系是:一个水库对应多个报汛站,每个报汛站每天都会录入一条降雨量的信息
现在用户可以选择多个水库,然后显示各个水库对应的所有的报汛站的最新的一条记录,怎么写?
条件是:where 表3.报汛站=表2.报汛站 and 表2.水库=表1.水库 and 表1.水库 in (一个数组变量) order by 时间 desc 就这样,我怎么select....?
这样吧,首先建立一个临时表:
create #tt(col1 int)
将你的条件数组得值放到#tt中,然后
select * form mytable t1 where date>=all(select date from mytable t2 where t2.id=t1.id) and 您的字段 in (select col1 from #tt)