【问题标题】:MySQL sorting distinct/unique valuesMySQL对不同/唯一值进行排序
【发布时间】:2020-12-10 17:10:34
【问题描述】:

决定将我的查询分解成小块,以帮助传达我想要实现的目标。

我有一些关于客户和他们使用的优惠券代码的信息,格式如下

Customer Coupon Code
1 FreeDel
1 FreeDel
1 FreeDel
1 1562733
1 8842939
1 847hr64
1 83jd63j
1 FreeDel
1 8eh33jr
1 AA-2637
1 AA-9837
1 Save200
1 Save200

我想对其进行排序:如果已知优惠券代码前缀可用,则使用如下语法:

CASE WHEN Coupon Code LIKE 'AA-%' THEN 'AA-' 优惠券代码唯一的情况,然后是“唯一” 优惠券代码不是唯一的情况,然后是“非唯一”

然后输出

Count Customer Coupon Code Type
6 1 Non-Unique
2 1 AA-
5 1 Unique

在这种理想情况下,首先添加已知前缀作为案例,然后将未知的、未重复的优惠券代码标记为唯一,然后将重复的优惠券代码标记为非唯一。

任何帮助将不胜感激! :)

表格编辑

【问题讨论】:

    标签: mysql sql database data-science


    【解决方案1】:

    您可以分别计算它们:

    select sum(cnt), customer, 'Non-Unique'
    from (
      select customer, coupon_code, count(*) as cnt
      from ccodes
      where coupon_code not like 'AA-%'
      group by customer, coupon_code
      having cnt>1
    ) as q
    group by customer
    union
    select count(*), customer, 'AA-'
    from ccodes
    where coupon_code like 'AA-%'
    group by customer
    union
    select sum(cnt), customer, 'Unique'
    from (
      select customer, coupon_code, count(*) as cnt
      from ccodes
      where coupon_code not like 'AA-%'
      group by customer, coupon_code
      having cnt=1
    ) as q
    group by customer
    

    db-fiddle

    【讨论】:

      【解决方案2】:

      您可以使用聚合和条件逻辑:

      (case when sum( code like 'AA-%' ) > 0 then 'AA-'
            when min(code) = max(code) then 'UNIQUE'
            else 'NON-UNIQUE'
       end)
      

      您可以将其合并到聚合查询中:

      select grp, count(*)
      from (select c.customer,
                   (case when sum( code like 'AA-%' ) > 0 then 'AA-'
                         when min(code) = max(code) then 'UNIQUE'
                         else 'NON-UNIQUE'
                    end) as grp,
                   count(*)
            from c
            group by customer
           ) x
      group by grp;
      

      【讨论】:

      • 我不关注 - 这将如何计算唯一和非唯一实例的数量?
      • @UsmaanBhatti 。 . .您可以将逻辑合并到聚合查询中。我编辑了答案。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-26
      相关资源
      最近更新 更多