简体   繁体   中英

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. 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
  • If there is more than one row of different type (one 'Acquired' and one 'Verified'), the row returned must be the 'Verified' one

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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