gpt4 book ai didi

sql-server - 在SQL中获取最近的较高和较低的行

转载 作者:行者123 更新时间:2023-12-03 23:14:13 25 4
gpt4 key购买 nike

我正在尝试选择高于 2000 的前 5 个金额和低于 2000 的前 5 个金额,并在单个结果集中返回数据。

SELECT TOP 5 * 
FROM bid
WHERE amount >= 2000
ORDER BY amount ASC
UNION
SELECT TOP 5 *
FROM bid
WHERE amount < 2000
ORDER BY amount DESC

看起来这不是 union 的使用方式,因为我遇到了运行时错误。

Incorrect syntax near the keyword 'union'.

编写所需查询的正确方法是什么?

最佳答案

SELECT * 
FROM (SELECT TOP 5 *
FROM bid
WHERE amount >= 2000
ORDER BY amount ASC) t1
UNION
SELECT *
FROM (SELECT TOP 5 *
FROM bid
WHERE amount < 2000
ORDER BY amount DESC) t2

您可以为结果添加额外的顺序:

SELECT * 
FROM (SELECT *
FROM (SELECT TOP 5 *
FROM bid
WHERE amount >= 2000
ORDER BY amount ASC) t1
UNION
SELECT *
FROM (SELECT TOP 5 *
FROM bid
WHERE amount < 2000
ORDER BY amount DESC) t2) t3
ORDER BY t3.amount

关于sql-server - 在SQL中获取最近的较高和较低的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21012616/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com