MSSQL不能有order by之后再用unite

问题:
查询信息表,信息表有两个字段————“状态state” “时间date”
要求:查询所有不同状态的最新时间数据,例如,01,02,03时间是最新的,两个条件
解决办法:
查询01状态的所有数据按照降序排列,获取第一个,
查询02状态的所有数据按照降序排列,获取第一个,
查询03状态的所有数据按照降序排列,获取第一个,
然后将三个使用Unit合并

代码:

select top 1 m.* from mon_rad_monreportinfo m where m.state='01' order by m.mon_date desc
union
select top 1 n.* from mon_rad_monreportinfo n where n.state='01' order by n.mon_date desc
union
select top 1 t.* from mon_rad_monreportinfo t where t.state='01' order by t.mon_date desc

 运行上面的代码报错,出现语法错误

修改之后的代码

select a.* from (select top 1 m.* from mon_rad_monreportinfo m where m.state='01' order by m.mon_date desc) a
union
select b.* from (select top 1 n.* from mon_rad_monreportinfo n where n.state='01' order by n.mon_date desc) b
union
select c.* from (select top 1 t.* from mon_rad_monreportinfo t where t.state='01' order by t.mon_date desc) c

 备注:查询虚拟表一定要有“别名”,否则会报错

猜你喜欢

转载自hbiao68.iteye.com/blog/1845994