下面的查询都可以单独工作,但在由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年前的那些日期。
答案 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;
上的索引可能会提高性能。