筛选出具有相同列的行

时间:2019-07-26 18:28:35

标签: mysql sql

我有一个复杂的查询,该查询返回一个表,该表的列具有一些重复的值,第二列具有整数。

这是数据的简单表示形式:

! diff pooutput.txt apdca-sd-rt01.txt > /dev/null && echo "NOT OK"

我的要求是选择col2值为null或按col1分组时的最小值的所有行。

因此,我的预期结果是:

col1   col2
===========
A      null
A      1
A      1
A      2
A      3

B      2
B      3

C      4

D      null

换句话说,对于col1中的每个不同值,在col2中找到相应的最小值,然后过滤出不为空且大于该值的所有行。

我尝试进行分组,但是当然可以合并行。我觉得这里缺少一个简单的解决方案。

2 个答案:

答案 0 :(得分:2)

您可以使用or和相关的子查询:

select t.*
from t
where t.col2 is null or
      t.col2 = (select min(t2.col2) from t t2 where t2.col1 = t.col1);

重复复杂的查询很麻烦。您还可以使用窗口功能执行此操作:

select col1, col2
from (select t.*, min(col2) over (partition by col1) as min_col2
      from t
     ) t
where col2 is null or col2 = min_col2;

答案 1 :(得分:1)

使用NOT EXISTS很简单:

select t.* from tablename t
where not exists (
  select 1 from tablename x
  where x.col1 = t.col1 and x.col2 < t.col2
)  

请参见demo
结果:

| col1 | col2 |
| ---- | ---- |
| A    | null |
| A    | 1    |
| A    | 1    |
| B    | 2    |
| C    | 4    |
| D    | null |