sql - 在执行 Select 查询时,如何忽略 Postgresql 中列具有特定值的数据行?

标签 sql postgresql

所以当我按某一列查询时,我有数据有时会返回多行,因为另一列不同。假设我想在第二列具有特定值但仅当另一行中存在其他值时忽略某些行。下面是一个例子

Name    Color
Tom     Blue
Tom     Red
Frank   Red

也就是说,当我在“名称”列下查询并将值为 Tom 时,我得到两行,其中一行的颜色为蓝色,另一行为红色。假设我只对颜色 Blue 感兴趣,所以我想忽略以 Red 作为值的行,但是只有当每个名称有多个 Color 实例时才如此。因此,例如,如果我在 Frank 下按名称查询,我不想仅仅因为颜色是红色而忽略该行。希望这是有道理的。

最佳答案

ROW_NUMBER 根据需要的优先级有条件地着色,例如,如果首选“蓝色”

select Name,Color 
from (
    select *, row_number() over(partition by name order by case color
                                when 'Red' then 2 
                                when 'Blue' then 1 end) rn
from dd
) t
where rn = 1   

当您需要除“红色”以外的所有颜色时,除了“红色”是唯一的颜色

select Name,Color 
from (
    select *, count(*) over (partition by name) as cnt
    from (
      /* example data*/
        select 'Tom' as Name,  'Blue' as Color
        union all
        select 'Tom' ,'Red'
        union all
        select 'Tom' ,'Green'
        union all
        select 'Frank' ,'Red'
        )dd
) t
where cnt = 1 or Color !='Red'

关于sql - 在执行 Select 查询时,如何忽略 Postgresql 中列具有特定值的数据行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41943641/

相关文章:

postgresql - 如何使用具有 JSONB 值的日期/时间函数?

postgresql - 专用数据库服务器重度 iowait 峰值

SQL - 连接两个单独的 sql 查询

sql - postgresql:不允许负子字符串长度,但数据中没有明显的违规

python - 在 SQLalchemy 中过滤正则表达式

sql - 为每一行比较 SQL 中的不同列

postgresql - 无法使用ansible创建postgres数据库

sql - SELECT DISTINCT 结果仅返回 COUNT > 1

sql - 在 MERGE 语句 ORACLE 中更新多列

mysql - 在 MySQL 中不使用 GROUP 获取 "#1111 - Invalid use of group function"