Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 从两个表中选择数据并按日期排序_Sql_Sql Server_Select_Union - Fatal编程技术网

Sql 从两个表中选择数据并按日期排序

Sql 从两个表中选择数据并按日期排序,sql,sql-server,select,union,Sql,Sql Server,Select,Union,我有两个数据表,需要合并它们并按日期排序。我有下面的问题,但工会一直给我一个错误 SELECT AssetTitle, AssetDate, AssetTeaser, AssetLink FROM pressAssets WHERE AssetType=1 ORDER BY AssetDate ASC UNION ALL SELECT BlogTitle, BlogDate, BlogEntry, BlogLink FROM blogTempTable ORDER BY Blo

我有两个数据表,需要合并它们并按日期排序。我有下面的问题,但工会一直给我一个错误

SELECT 

AssetTitle,
AssetDate,
AssetTeaser,
AssetLink

FROM pressAssets WHERE AssetType=1 ORDER BY AssetDate ASC

UNION ALL

SELECT

BlogTitle,
BlogDate,
BlogEntry,
BlogLink


FROM

blogTempTable ORDER BY BlogDate ASC, AssetDate ASC;
有人能帮我吗?

使用子查询:

select *
from
(
    SELECT 

    AssetTitle,
    AssetDate,
    AssetTeaser,
    AssetLink

    FROM pressAssets WHERE AssetType=1 

    UNION ALL

    SELECT

    BlogTitle,
    BlogDate,
    BlogEntry,
    BlogLink


    FROM

    blogTempTable
)a
ORDER BY AssetDate ASC;

对于联合结果集,您只允许使用一个
ORDER BY
。您不能单独对这两个查询排序。

您的代码不能按原样工作。这将得到一个结果集,但日期字段都合并在一起;应用
联合后,无法区分源

SELECT 
  Title,
  Date,
  Teaser,
  Link

FROM (
SELECT 

AssetTitle Title,
AssetDate Date,
AssetTeaser Teaser,
AssetLink Link

FROM pressAssets WHERE AssetType=1 

UNION ALL

SELECT

BlogTitle Title,
BlogDate Date,
BlogEntry Teaser,
BlogLink Link


FROM

blogTempTable) T

ORDER BY Date ASC;
我认为:

Select * from 
(
SELECT AssetTitle as mtitle, AssetDate as mdate, 
AssetTeaser as mtease, AssetLink as mlink
FROM pressAssets 
WHERE AssetType=1
UNION
SELECT BlogTitle as mtitle, BlogDate as mdate,
BlogEntry as mtease, BlogLink, as mlink
FROM blogTempTable
)
ORDER BY mdate
很接近


编辑:这与Yuck的更正答案的方法相同。

order by
中删除了
BlogDate
,因为它在
Union
@phlogratos:谢谢帮助:)我尝试了你的解决方案,但它在“as”部分不断抛出错误。我确信“Union error”不是有效的SQL Server错误消息。接下来,请将完整的错误信息与您的问题一起发布“UNION附近语法不正确”似乎是UNION附近的错误,所以我个人认为这是UNION错误。