"WHERE"子句,"IN"



我正在尝试(在Impala SQL上)获得两列之间最大/最小差异的行,我正在尝试这样的东西:

SELECT * 
FROM table 
WHERE col1 - col2 IN ( SELECT MAX(col1-col2) 
FROM table, SELECT MIN(col1-col2) FROM table )

只使用一个子查询工作,但如果我在IN中添加它们,它会给出一个错误。

有什么建议吗?

使用子查询连接:

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)

在这种情况下,您不能使用"in"就像你需要将它们连接在一起,或者将它们合并为列表。我给你看一些例子

SELECT * FROM table WHERE  col1 - col2 IN ( SELECT MAX(col1-col2) FROM table  union  SELECT MIN(col1-col2) FROM table)

希望它能帮到你。

使用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

我更喜欢使用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)

最新更新