我正在尝试(在 Impala SQL 上)获取两列之间差异最大/最小的行,我正在尝试这样的事情:
SELECT *
FROM table
WHERE col1 - col2 IN ( SELECT MAX(col1-col2)
FROM table, SELECT MIN(col1-col2) FROM table )
仅使用一个子查询有效,但如果我将它们都添加到 IN 中,则会出错。
关于我如何做到这一点的任何建议?
答案 0 :(得分:2)
使用子查询连接:
SELECT *
FROM table t
JOIN (
SELECT MIN(col1 - col2) AS min_diff, MAX(col1 - col2) AS max_diff
FROM table
) AS agg ON t.col1 - t.col2 IN (agg.min_diff, agg.max_diff)
答案 1 :(得分:0)
使用 union
如下:
SELECT * FROM table WHERE col1 - col2 IN ( SELECT MAX(col1-col2) FROM table
Union
SELECT MIN(col1-col2) FROM table )
-- 更新
使用 rank
如下:
SELECT t.*,
Rank() over (order by col1 - col2) as rn,
Rank() over (order by col1 - col2 desc) as rnd
FROM table t) t
Where rn = 1 or rnd = 1
答案 2 :(得分:0)
在您的情况下,您不能像这样使用“in”,您需要将它连接在一起或将其合并为列表。我给你看一些例子
SELECT * FROM table WHERE col1 - col2 IN ( SELECT MAX(col1-col2) FROM table union SELECT MIN(col1-col2) FROM table)
希望它会帮助你。
答案 3 :(得分:0)
我更喜欢使用 CTE,如下所示:
with difference as
(
select min(col1-col2) minDifference,max(col1-col2) maxDifference
from table
)
select *
from table as t
join difference as d
where t.col1-t.col2 in (d.minDifference,d.maxDifference)