combining resultset obtained by select statements to create a view

谁说胖子不能爱 提交于 2019-12-12 00:29:19

问题


I have 4 Select statements for 4 different tables each Select query gives latest record meeting specified condition for ex:

Select TOP 1 * from table where column_name = 'something' order by col1 DESC;

Now I have to combine result set of all 4 queries and create a view from combined result set.


回答1:


Some DB's don't let you provide an "order by" clause inside on of the unioned queries.

If you're ordering by col1 desc, it's possible that it's some type of column you can apply min() or max() to.

If that is the case, below could solve your issue (if there aren't too many records, or, if the tables are massive, "col1" and "some_column" are indexed.)

create view some_view as
(
select * from table1
  where some_column = 'something'
  and col1 = (select max(col1) from table1 where some_column = 'something')
UNION ALL
select * from table2 
  where some_column = 'something'
  and col1 = (select max(col1) from table2 where some_column = 'something')
UNION ALL
select * from table3 
  where some_column = 'something'
  and col1 = (select max(col1) from table3 where some_column = 'something')
UNION ALL
select * from table4 
  where some_column = 'something'
  and col1 = (select max(col1) from table4 where some_column = 'something')
)



回答2:


create view some_view as
(
(select TOP 1 * from table1 where ....)
UNION ALL
(select TOP 1 * from table2 where ....)
UNION ALL
(select TOP 1 * from table3 where ....)
UNION ALL
(select TOP 1 * from table4 where ....)
)


来源:https://stackoverflow.com/questions/11876790/combining-resultset-obtained-by-select-statements-to-create-a-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!