sql - 选择具有优先级值的非重复行

标签 sql sql-server select duplicates

我有一个表格,其中包含带有测量值的行。对于同一个batch id,可以指定多个measure。我想在以下条件下获得正确的值:

  • 如果给定的批处理只有一行,则该度量有效
  • 如果同一类型的行不止一行,则度量无效,返回的类型应为“无效”,值 = 0
  • 如果有不止一行的不同类型(一个'Acquired'和一个'Verified'),返回的行必须是'Verified'的行

示例数据:

create table measures (
  batch  int,
  type   varchar(24),
  value int
);

insert into measures select 01,'Verified',10;
insert into measures select 02,'Acquired',34;
insert into measures select 03,'Verified',22;
insert into measures select 03,'Verified',24;
insert into measures select 04,'Verified',32;
insert into measures select 04,'Acquired',34;
insert into measures select 05,'Acquired',42;
insert into measures select 05,'Acquired',44;

示例输出:

01   Verified   10
02   Acquired   34
03   Invalid    0
04   Verified   32
05   Invalid    0

最佳答案

你的逻辑有点难以理解。您可以使用条件聚合来做您想做的事。它认为逻辑是:

select batch,
       (case when count(*) = 1 then max(type)
             when min(type) = max(type) then 'Invalid'
             else coalesce(max(case when type = 'Verified' then 'Verified' end), 'Invalid')
        end) as type,
       (case when count(*) = 1 then max(value)
             when min(type) = max(type) then 0
             else coalesce(max(case when type = 'Verified' then value end), 0)
        end) as value
from measures m
group by batch;

关于sql - 选择具有优先级值的非重复行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59789107/

相关文章:

mysql - 硬连接查询

sql - "Results to Text"选项中设置的 SQL Server 中的自定义分隔符不起作用

sql - 删除特定值的列

mysql - 如何将 500,000 个随机值插入到 My SQL 的列中?

javascript - 在选择标签而不是文本中显示值

java - 找不到使用 jOOQ 在 CommonTableExpression 中选择数据的正确方法

php - 整数相加奇怪的结果

ios - 将从iPad/iPhone拍摄的图像保存到sql server数据库base64

javascript - 选择更改图像和链接

ruby-on-rails - rails : fields_for select