基于条件的不同sql [英] Distinct sql based on condition

查看:41
本文介绍了基于条件的不同sql的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是表结构.第一列包含可能出现在多行中的字符串.我想以这样的方式编写查询, column1 值只重复一次,以便 column2 包含 A 的行优先.如果只有 B 可用,则输出相同.

Below is the table structure. Column one contains strings which might be present in more than one row. I want to write a query in such a way column1 value is only repeated once such that row where column2 contains A takes priority. If only B is available output the same.

下面提供了示例数据和预期的 sql 输出.

Sample Data is provided below and expected sql output.

表格结构(还有其他列,这里略过)

Table Structure (there are other columns as well which is skipped here)

Column1 Column2
 123       A
 234       A
 234       B
 435       A
 536       B

SQL 预期输出

Column1 Column2
 123       A
 234       A
 435       A
 536       B

推荐答案

试试这个查询:

SELECT Column1, MIN(Column2) AS Column2
FROM yourTable
GROUP BY Column1
ORDER BY Column1;

演示

这应该有效,因为如果两个值都存在,MIN 将始终选择 A 而不是 B.

This should work because MIN would always select A over B, should both values be present.

这篇关于基于条件的不同sql的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆