问题
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