将二进制值分配给 SQL 中的重复项

Assigning Binary Values to duplicates in SQL

我有以下table

Animal 
dog
dog
dog
cat
cat

我想 运行 一个通过分配二进制值导出以下内容的查询。

Animal Unique
dog    1
dog    0
dog    0
cat    1
cat    0

我尝试在分区上使用 row_number,但我需要后续值为零。

我需要这个,因为它将连接到电源查询和一个数据透视表 table,我想在其中对列求和,以便我看到动物的独特数量

一点也不漂亮,但它工作...

Select fullList.Animal, case when mr is not null then 1 else 0 end as uniq from 
  (SELECT min(rank) mr, animal
  FROM (SELECT A.*, @rownum := @rownum + 1 AS rank
      FROM t1 A
      CROSS JOIN (SELECT @rownum := 0) r
      ORDER BY ANIMAL) B
  GROUP BY ANIMAL) SubSet
RIGHT JOIN 
(SELECT A.*, @rwnum := @rwnum + 1 AS rank
      FROM t1 A
      CROSS JOIN (SELECT @rwnum := 0) r
      ORDER BY ANIMAL) FullList
on FullList.Animal = SubSet.Animal
and FullList.Rank = SubSet.mr

http://sqlfiddle.com/#!9/cc5386/13/0

抛开奇怪的 table 设计,您可以使用前面的行来执行此操作。基本上,如果当前行中的动物=前一行中的动物,则将其设置为0,否则将其设置为1.

    create multiset  volatile table vt (animal varchar(10))
    on commit preserve rows;
    insert into vt values ( 'cat'  );

    select 
    animal,
    case when max(animal) over (partition by animal order by animal 
    rows between 1 preceding and 1 preceding) = animal then 0 else 1 end as test
    from vt order by animal, test desc

哪个会给你:

cat 1
cat 0
dog 1
dog 0
dog 0

您使用 row_number 关闭,只需使用 case:

select animal,
   case when row_number() 
             over (partition by animal order by animal) = 1 
        then 1 
        else 0 
   end
from t1