【问题标题】:SQL select distinct dataSQL 选择不同的数据
【发布时间】:2018-02-18 17:57:23
【问题描述】:

我是 SQL 的新手,找不到我的问题的答案。我只有一个大表,需要从中提取两个不同的列以及其他一些列的额外数据。

示例:

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 和大小的列。所以我需要这样的答案:

结果:

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

我尝试加入表格,但没有成功。

【问题讨论】:

  • 目标是 MySQL 5.5。但查询应该是简单而通用的“可能变化的余数”
  • 选择另外两列例如大小的标准是什么?应该是最大尺寸还是最小尺寸?

标签: mysql sql select distinct


【解决方案1】:

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

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>

【讨论】:

  • @Littlefoot 为什么使用 min 作为 id 而使用 max 作为 size?
  • 因为这就是 OP 的“结果”所建议的,@sia。从我的角度来看,在这两种情况下都可能是 MAX 或 MIN,只是结果必须显示不同的动物、它的颜色和它可能具有的 任何 大小 - 我选择了 MAX。截至 ID,我第一次出现在 [animal + color] 组合中(“first”在此上下文中表示“MIN”)。
【解决方案2】:

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

选择动物、颜色、尺寸 ( 选择动物,颜色,大小,row_number() over (partition by animal, color order by size) as rowx 从表名 ) as X where rowx = 1;

【讨论】:

  • 您能否在答案中添加格式,以便您的代码部分更易于阅读。
猜你喜欢
  • 2022-01-16
  • 2011-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-20
相关资源
最近更新 更多