按特殊条件分组以选择行

时间:2019-09-15 04:28:53

标签: sql oracle

我的桌子

Id | Add  | Check | RESULT | Seq
__________________________________________
1  | 2    | 1     | 1      | 10
1  | 2    | 1     | 2      | 20
2  | 3    | 4     | 4      | 30
2  | 3    | 4     | 4      | 40
3  | 5    | 2     | 2      | 50
4  | 2    | 6     | 2      | 60

我想要这个结果。

Id | Add  | Check | RESULT | Seq
__________________________________________
1  | 2    | 1     | 2      | 20
2  | 3    | 4     | 4      | 30
3  | 5    | 2     | 2      | 50
4  | 2    | 6     | 2      | 60

我要这样查询

Select 
(if add==result then return row else return row with min(seq) ) 
From MyTable 
Group by Id.

请帮助我...

3 个答案:

答案 0 :(得分:3)

此查询将为您提供所需的结果。它会寻找以下行:Add = Result,或其中Seq是该Add值的最小值,但仅在不存在与第一个条件匹配的行的情况下:

SELECT *
FROM mytable m1
WHERE "Add" = "RESULT"
   OR "Seq" = (SELECT MIN("Seq") FROM mytable m2 WHERE m2."Add" = m1."Add")
  AND NOT EXISTS (SELECT * FROM mytable m3 WHERE m3."Add" = m1."Add" AND m3."Add" = m3."RESULT")

输出:

Id  Add     Check   RESULT  Seq
1   2       1       2       20
2   3       4       4       30
3   5       2       2       50
4   2       6       2       60

Demo on dbfiddle

答案 1 :(得分:1)

您可以按以下方式使用分析功能:

SELECT ID, ADD, CHECK, RESULT,
       CASE WHEN ADD = RESULT THEN SEQ ELSE MIN_SEQ END AS SEQ 
 FROM
   (SELECT ID, ADD, CHECK, RESULT,
           ROW_NUMBER() OVER (PARTITION BY ID ORDER BY CASE WHEN ADD = RESULT THEN 1 ELSE 0 END) AS RESULT_RN,
           SEQ, MIN(SEQ) OVER (PARTITION BY ID) MIN_SEQ
      FROM YOUR_TABLE)
WHERE RESULT_RN = 1;

干杯!

答案 2 :(得分:1)

我可以使用row_number()

select t.*
from (select t.*,
             row_number() over (partition by id
                                order by (case when add = result then 1 else 2 end),
                                         seq
                               ) as seqnum
      from t
     ) t
where seqnum = 1;

如果在add = result处可以有重复的行,则可以对其进行调整以处理该行。