"WHERE" 子句在 "IN" 中

"WHERE" clause with subqueries in "IN"

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

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

只使用一个子查询是可行的,但如果我将它们都添加到 IN 中,则会出错。

有什么关于如何做到这一点的建议吗?

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

在您的情况下,您不能像需要将其连接在一起或将其合并为列表那样使用“in”。我给你举个例子

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

希望它能帮到你。

使用子查询连接:

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)

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