查询以获取某些条件记录

时间:2013-07-21 13:12:53

标签: sql sybase

我有以下表格数据

ID         Type Code     Opt    Line    Status

26985444    1   100        1       1    S0
26987422    1   25         1       1    S0
26987422    1   25         2       1    S1
26987422    1   25         2       2    S2
26987422    4   25         2       3    S0
26987422    2   30         1       1    S1
26987422    2   30         1       2    S2
26987422    2   30         1       3    S0
26987422    3   35         1       1    S0
26985333    1   75         1       1    S0
26985000    1   55         1       1    S0
26985000    1   65         1       1    S0

除此之外,我只需要选择以下记录

26985444    1   100 1   1   S0
26985333    1   75  1   1   S0

如何为此编写SQL查询。

由于

2 个答案:

答案 0 :(得分:0)

我在上表中看到的唯一排序是,如果您在Code字段转换为char()时进行排序。您可以使用max()min()来猜测您可能正在寻找的内容:

select y.* 
from yourtable y
  join (
    select max(cast(Code as char(3))) maxCode,
      min(cast(Code as char(3))) minCode
    from yourtable
    ) t on y.code = t.maxCode or y.code = t.minCode

答案 1 :(得分:0)

我将您的问题解释为查找仅在数据中出现一次的ID

你可以通过聚合来寻找单身人士:

select ID, min(Type) as Type, min(Code) as Code, min(Opt) as Opt,
       min(Line) as Line, min(Status) as Status
from t
group by id
having count(*) = 1;

如果您的Sybase版本支持窗口功能:

select ID, Type, Code, Opt, Line, Status
from (select t.*,
             count(*) over (partition by id) as cnt
      from t
     ) t
where cnt = 1
相关问题