首页 文章

SQL选择不同的数据

提问于
浏览
-1

我是SQL的新手,无法找到我的问题的答案 . 我只有一个大表,需要从其中提取两个不同的列,其中包含来自其他列的额外数据 .

Example:

table1

id  animal  color   size     name, breed etc
1   cat     white   medium
2   cat     white   big
3   dog     white   medium
5   dog     white   big
6   cat     black   small
7   cat     black   small

我要求“选择不同的...”用于动物和颜色以及另外两个具有id和大小的列 . 所以我需要这样的回答:

Result:

1  cat  white  medium
3  dog  white  medium
6  cat  black  small

我试过加入表,但没有成功 .

2 回答

  • 0

    根据你所描述的,这样的事情可能会起作用:

    SQL> with test (id, animal, color, c_size) as
      2  (select 1, 'cat', 'white', 'medium' from dual union
      3   select 2, 'cat', 'white', 'big'    from dual union
      4   select 3, 'dog', 'white', 'medium' from dual union
      5   select 5, 'dog', 'white', 'big'    from dual union
      6   select 6, 'cat', 'black', 'small'  from dual union
      7   select 7, 'cat', 'black', 'small'  from dual
      8  )
      9  select min(id) id, animal, color, max(c_size) c_size
     10  from test
     11  group by animal, color;
    
            ID ANI COLOR C_SIZE
    ---------- --- ----- ------
             1 cat white medium
             3 dog white medium
             6 cat black small
    
    SQL>
    
  • 0

    这可以使用over()分区子句来实现 .

    选择动物,颜色,大小(选择动物,颜色,大小,row_number()(按动物划分,颜色顺序按大小)作为tablex中的rowx)为X,其中rowx = 1;

相关问题