我有一张这样的表
假设该表是show_date
different | date
----------------------
-2 | 2011-04-18
----------------------
-1 | 2011-04-19
----------------------
4 | 2011-04-24
----------------------
5 | 2011-04-25
----------------------
我想选择2个值,第一个是第一个负值,第二个是第一个正值。 在此示例中将得到-1(2011-04-19)和4(2011-04-24)
我尝试通过abs(不同)进行排序,但它给出最近的2,即-1和-2
答案 0 :(得分:4)
(SELECT * FROM show_date WHERE different < 0 ORDER BY different DESC LIMIT 1)
UNION ALL
(SELECT * FROM show_date WHERE different >= 0 ORDER BY different LIMIT 1)
答案 1 :(得分:3)
SELECT
MIN(CASE WHEN different > 0 THEN different ELSE NULL END) AS MinPositive,
MAX(CASE WHEN different < 0 THEN different ELSE NULL END) AS MaxNegative
FROM show_date
答案 2 :(得分:1)
SELECT
min (a.nr),
max (b.nr)
FROM
demo a,
demo b
WHERE a.nr > 0
AND b.nr < 0;
min | max
-----+----
1 | -1
(1 Row)
另一种方法 - 上述解决方案对于大型表来说会产生问题:
SELECT min(date)
FROM tbl
WHERE date > 0
UNION
SELECT max(date)
FROM tbl
WHERE date < 0;