这句话有什么问题?我收到以下错误:
第15行,第1行,第4行 关键字“ORDER”附近的语法不正确。
第15行,第15行,第1行,第9行 关键字“ORDER”附近的语法不正确。
(SELECT TOP 1 dbo.ZERORATES.Maturity_Date AS Date1, dbo.ZERORATES.Zero_Rate AS Rate1
FROM dbo.ZERORATES
WHERE dbo.ZERORATES.Maturity_Date < '2013-05-16'
ORDER BY dbo.ZERORATES.Maturity_Date DESC)
UNION
(SELECT TOP 1 dbo.ZERORATES.Maturity_Date AS Date2, dbo.ZERORATES.Zero_Rate AS Rate2
FROM dbo.ZERORATES
WHERE dbo.ZERORATES.Maturity_Date > '2013-05-16'
ORDER BY dbo.ZERORATES.Maturity_Date ASC)
答案 0 :(得分:8)
尝试将您的查询嵌入选择
select * from
(SELECT TOP 1 dbo.ZERORATES.Maturity_Date AS Date1, dbo.ZERORATES.Zero_Rate AS Rate1
FROM dbo.ZERORATES
WHERE dbo.ZERORATES.Maturity_Date < '2013-05-16'
ORDER BY dbo.ZERORATES.Maturity_Date DESC) as T
UNION
select * from
(SELECT TOP 1 dbo.ZERORATES.Maturity_Date AS Date2, dbo.ZERORATES.Zero_Rate AS Rate2
FROM dbo.ZERORATES
WHERE dbo.ZERORATES.Maturity_Date > '2013-05-16'
ORDER BY dbo.ZERORATES.Maturity_Date ASC) as T
答案 1 :(得分:1)
UNION只能有一个订单,只能在最后一个选择中,子查询只能有1列,将其更改为:
SELECT TOP 1 dbo.ZERORATES.Maturity_Date AS Date1, dbo.ZERORATES.Zero_Rate AS Rate1
INTO #Temp1
FROM dbo.ZERORATES
WHERE dbo.ZERORATES.Maturity_Date < '2013-05-16'
ORDER BY dbo.ZERORATES.Maturity_Date DESC
UNION
SELECT TOP 1 dbo.ZERORATES.Maturity_Date AS Date1, dbo.ZERORATES.Zero_Rate AS Rate1
INTO #Temp2
FROM dbo.ZERORATES
WHERE dbo.ZERORATES.Maturity_Date > '2013-05-16'
ORDER BY dbo.ZERORATES.Maturity_Date ASC
SELECT * FROM #Temp1
UNION
SELECT * FROM #Temp2
答案 2 :(得分:0)
ORDER BY在视图EDIT(仅在SQLServer中)中无效,除非指定了SELECT TOP / EDIT。在加入表格后尝试订购结果集。
答案 3 :(得分:0)
UNION只能有一个ORDER,以获得可以使用MIN和MAX的顶部和底部值
SELECT MAX(dbo.ZERORATES.Maturity_Date) AS Date, dbo.ZERORATES.Zero_Rate AS Rate
FROM dbo.ZERORATES
WHERE dbo.ZERORATES.Maturity_Date < '2013-05-16'
GROUP BY dbo.ZERORATES.Zero_Rate
UNION
SELECT MIN(dbo.ZERORATES.Maturity_Date) AS Date, dbo.ZERORATES.Zero_Rate AS Rate
FROM dbo.ZERORATES
WHERE dbo.ZERORATES.Maturity_Date > '2013-05-16'
GROUP BY dbo.ZERORATES.Zero_Rate
答案 4 :(得分:0)
如果每个日期的行数不超过1行,则会执行以下操作:
SELECT z.Maturity_Date AS Date
, z.Zero_Rate AS Rate
FROM
dbo.ZERORATES z
JOIN
( SELECT MAX(dbo.ZERORATES.Maturity_Date) AS D
FROM dbo.ZERORATES
WHERE dbo.ZERORATES.Maturity_Date < '2013-05-16'
UNION
SELECT MIN(dbo.ZERORATES.Maturity_Date) AS D
FROM dbo.ZERORATES
WHERE dbo.ZERORATES.Maturity_Date > '2013-05-16'
)
AS maxmin
ON z.Maturity_Date = maxmin.D
我确信使用OVER()
和PARTITION BY
有更优雅的解决方案,但我现在不在SQL服务器附近进行检查。