简体   繁体   English

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

[英]SELECT non duplicated rows with priority value

I have a table that contains rows with measurements.我有一个包含带有测量值的行的表。 For the same batch id, more than one measure can be specified.对于同一个批次 ID,可以指定多个度量。 I want to get the correct values under the following conditions:我想在以下条件下获得正确的值:

  • If there is only one row for a given batch, the measure is valid如果给定批次只有一行,则度量有效
  • If there is more than one row of the same type, the measure is NOT valid and the type returned should be 'Invalid', with value = 0如果相同类型的行不止一行,则度量无效,返回的类型应为“无效”,值 = 0
  • If there is more than one row of different type (one 'Acquired' and one 'Verified'), the row returned must be the 'Verified' one如果不同类型的行不止一行(一个是“Acquired”,一个是“Verified”),则返回的行必须是“Verified”行

Sample data:样本数据:

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;

Sample output:示例输出:

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

Your logic is a bit hard to follow.你的逻辑有点难以理解。 You can do what you want with conditional aggregation.您可以使用条件聚合做您想做的事情。 It think the logic is:它认为的逻辑是:

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;

Using windows functions:使用窗口函数:

;WITH CountTypesPerBatch AS
(
    SELECT batch, type, value,
           COUNT(CASE WHEN type = 'Verified' THEN 1 END) 
              OVER (PARTITION BY batch) AS verified,
           COUNT(CASE WHEN type = 'Acquired' THEN 1 END) 
              OVER (PARTITION BY batch) AS acquired,
           ROW_NUMBER() OVER (PARTITION BY batch 
                              ORDER BY IIF(type='Verified',1, 2)) seq
    FROM measures
)
SELECT DISTINCT batch, 
       CASE 
          WHEN verified > 1 OR acquired > 1 THEN 'invalid' 
          WHEN verified = 1 THEN 'verified'
          ELSE 'acquired'
       END,
       CASE 
          WHEN verified > 1 OR acquired > 1 THEN 0
          ELSE value
       END
FROM CountTypesPerBatch
WHERE seq = 1

Demo here演示在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM