我必须从不同的表中获取最新的前1项,并根据desc中的日期对结果进行排序,然后根据日期选择前1条记录
SELECT TOP 1 PublishDate, 'Article' FROM Articles ORDER BY PublishDate
UNION ALL
SELECT TOP 1 PublishDate, 'News' FROM News ORDER BY NewsDate
UNION ALL
SELECT TOP 1 CreateDate, 'Blog' FROM Blog ORDER BY BlogDate
UNION ALL
SELECT TOP 1 PostDate, 'Videos' FROM Videos ORDER BY NewsDate
结果我应该根据最新发布日期有最新的1条记录。
我尝试在存储过程的所有语句中使用ORDER BY
,但它不起作用,因为它会引发错误。如何使用此查询或CTE查询获得所需结果。
我正在使用SQL Server 2008
答案 0 :(得分:2)
尝试制作另一个子选择:
select top 1 date, type from
(SELECT
TOP 1 PublishDate as date, 'Article' as type
FROM Articles
ORDER BY PublishDate
UNION ALL SELECT
TOP 1 PublishDate as date, 'News' as type
FROM News ORDER BY NewsDate
UNION ALL SELECT TOP 1 CreateDate as date, 'Blog' as type
FROM Blog ORDER BY BlogDate
UNION ALL SELECT TOP 1 PostDate as date, 'Videos' as type
FROM Videos ORDER BY NewsDate) as unions
order by date
答案 1 :(得分:0)
这个怎么样:
select * from
(SELECT TOP 1 PublishDate, 'Article' as description FROM Articles
UNION ALL
SELECT TOP 1 PublishDate, 'News' FROM News
UNION ALL
SELECT TOP 1 CreateDate, 'Blog' FROM Blog
UNION ALL
SELECT TOP 1 PostDate, 'Videos' FROM Videos) as a ORDER BY description