I have a table like this
let say the table is开发者_Python百科 show_date
different | date
----------------------
-2 | 2011-04-18
----------------------
-1 | 2011-04-19
----------------------
4 | 2011-04-24
----------------------
5 | 2011-04-25
----------------------
I want to select 2 values, the first one is the first negative value and the second one is the first positive value. in this sample will result -1 (2011-04-19) and 4 (2011-04-24)
I've try order by abs(different) but it give the 2 nearest which is -1 and -2
(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)
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
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)
An alternative approach - above solution gets problematic for large tables:
SELECT min(date)
FROM tbl
WHERE date > 0
UNION
SELECT max(date)
FROM tbl
WHERE date < 0;
精彩评论