sql创建唯一值标志

zsohkypk  于 2021-06-17  发布在  Mysql
关注(0)|答案(3)|浏览(286)

有很多关于在mysql查询中选择唯一值的问题/答案,但是我没有看到任何关于创建唯一值标志的问题/答案。
我有一个客户id,它可以在查询输出中出现多次。我想创建一个新列来标记customer\u id是否唯一(0或1)。
输出应该如下所示:

ID     | Customer ID      | Unique_Flag
1      | 1234             | 1
2      | 2345             | 1
3      | 2345             | 0
4      | 5678             | 1

如果有人需要澄清,请告诉我。

ht4b089n

ht4b089n1#

你可以在下面试试

select id,a.customerid, case when cnt=1 then 1 else 0 end as Unique_Flag
from tablename a 
left join 
(select customerid, count(*) as cnt from tablename
group by customerid
)b on a.customerid=b.customerid
soat7uwm

soat7uwm2#

您似乎想将第一个事件标记为唯一的,而不是其他事件。那么,让我们加入比较值:

select t.*,
       (id = min_id) as is_first_occurrence
from t join
     (select customer_id, min(id) as min_id
      from t
      group by customer_id
     ) tt
     on t.customer_id = tt.customer_id;

对大多数人来说,“唯一”标志意味着总计数是“1”,而不是仅仅是第一次出现。如果这就是你想要的,那么你可以使用类似的逻辑:

select t.*,
       (id = min_id) as is_first_occurrence,
       (cnt = 1) as is_unique
from t join
     (select customer_id, min(id) as min_id, count(*) as cnt
      from t
      group by customer_id
     ) tt
     on t.customer_id = tt.customer_id;

在mysql 8+中,您将使用窗口函数:

select t.*,
       (row_number() over (partition by customer_id order by id) = 1) as is_first_occurrence,
       (count(*) over (partition by customer_id) = 1) as is_unique
from t;
a8jjtwal

a8jjtwal3#


您可以使用下面给出的lead函数来获得所需的输出。 SELECT ID, CUSTOMER_ID, CASE WHEN CUSTOMER_ID != CUSTOMER_ID_NEXT THEN 1 ELSE 0 END AS UNIQUE_FLAG FROM (SELECT ID, CUSTOMER_ID,LEAD(CUSTOMER_ID, 1, 0) OVER (ORDER BY CUSTOMER_ID) AS CUSTOMER_ID_NEXT FROM TABLE)T

相关问题