为什么这些子查询单独工作,但在使用UNION时却不能工作?

时间:2019-06-11 22:21:06

标签: sql ms-access

下面的查询都可以单独工作,但在由Union子句连接时却不能工作。而不是列出最近的4个日期和去年的相同4个日期,它返回表中最近的4个日期,然后是最旧的4个日期。

查询1

SELECT DISTINCT TOP 4 [Week Ending]
FROM [DataFormat]
ORDER BY [Week Ending] DESC;

查询2

SELECT DISTINCT TOP 4 [Week Ending]
FROM [DataFormat]
WHERE [Week Ending] < DateAdd('yyyy',-1,(SELECT MAX([Week Ending]) FROM [DataFormat]))
ORDER BY [Week Ending] DESC;

这是行不通的查询:

SELECT DISTINCT TOP 4 [Week Ending]
FROM [DataFormat]
ORDER BY [Week Ending] DESC;
UNION ALL
SELECT DISTINCT TOP 4 [Week Ending]
FROM [DataFormat]
WHERE [Week Ending] < DateAdd('yyyy',-1,(SELECT MAX([Week Ending]) FROM [DataFormat]))
ORDER BY [Week Ending] DESC;

我想要一列最近的n日期和1年前的那些日期。

2 个答案:

答案 0 :(得分:4)

保存两个SELECT查询。用这两个查询对象构建一个UNION查询。

SELECT Query1.* FROM Query1
UNION
SELECT Query2.* FROM Query2;

不打算尝试理解和解释为什么多合一查询不起作用。

答案 1 :(得分:0)

您可以执行以下操作:

CC=gcc-8 pip install clickhouse-cityhash

SELECT DISTINCT [Week Ending] FROM [DataFormat] WHERE [Week Ending] IN (SELECT DISTINCT TOP 4 [Week Ending] FROM [DataFormat] ORDER BY [Week Ending] DESC ) OR [Week Ending] IN (SELECT DISTINCT TOP 4 [Week Ending] FROM [DataFormat] WHERE [Week Ending] < DateAdd('yyyy', -1, (SELECT MAX([Week Ending]) FROM [DataFormat]) ) ORDER BY [Week Ending] DESC; 上的索引可能会提高性能。