sql - 对具有不同值的两个字段进行分组,并按顺序选择特定值
问题描述
我一直在寻找这个问题的解决方案,但仍然找不到比这个SQL Group BY COLUMN Choose specific rows最相似的问题。
所以这是我的问题
Type_Table
column1 | column2
a | s
a | m
a | e
b | s
b | e
c | m
c | s
所以基本上我想按column1分组,但只选择column2 = e中的值,但如果column1中的重复值不存在则选择column2 = s,但如果重复值column1中不存在则选择column2 = 米。所以结果表看起来像这样
column1 | column2
a | e
b | e
c | s
我用过这个
select column1,case when column2=e then e when column2=s then s when column2=m then m end column2 from type_table group by 1
,但显然行不通。我需要的是按column1分组,对于column2中的每个不同值,如果它们各自的column1值存在则只选择e,但如果e不存在则选择s,如果s不存在则选择m。感谢您的回答
解决方案
一种方法使用row_number()
:
select t.*
from (select t.*,
row_number() over (partition by col1
order by (case col2 when 'e' then 1 when 's' then 2 when 'm' then 3 else 4 end)
) as seqnum
from t
) t
where seqnum = 1;
推荐阅读
- flutter - Flutter 中的窗口是否可复制
- oracle - ASH: IN_PARSE 和 IN_SQL_EXECUTION 同时?
- python - 为什么使用正则表达式的 str.match 在 Pandas 中不起作用
- batch-file - 用户只能按数字文件夹选择列表
- vb.net - 图表未正确绘制数据 (Visual Basic)
- facebook - 如何解决 facebook 登录插件配置器错误?
- azure - 针对 azure devops 服务连接授权管道
- apache-kafka - 需要识别空闲的 kafka 消费者
- php - 从php中的2个数组中找到唯一的数组
- search - 如何在gvim中搜索单词但替换上面一行中的字符