【问题标题】:Mark duplicated values MySQL without using GROUP BY在不使用 GROUP BY 的情况下标记重复值 MySQL
【发布时间】:2020-07-13 13:54:04
【问题描述】:

您能否帮助在附加列中标记重复值而不对重复值进行分组?

查看我的示例数据(右侧示例我拥有什么以及我需要实现什么):

如您所见,我的产品 ID 带有后缀 E(电源)和 G(气体)。一些产品 ID 是重复的:相同的产品 ID - 一个带有 E,第二个带有 G 构成双重产品

只有 E 的产品 ID 构成 Power_Only_product,只有 G 的产品 ID 构成 Gas_Only_product,相同的产品带有 EG 的 ID 构成 双重产品

棘手的事情是在正确的站点上添加一个列,其中包含 ID 是双产品的信息,以及哪一个是 Power Only 或 Gas Only。

您能帮我在不对产品 ID 进行分组的情况下获得这样的列吗? 先感谢您!帕维尔

【问题讨论】:

    标签: mysql sql select duplicates


    【解决方案1】:

    如果您运行的是 MySQL 8.0,则可以仅使用窗口函数执行此操作,而无需连接、子查询或 CTE。

    我建议只比较每个客户的product 的最大值和最小值;当它们不同时,您就有了“双重产品”。

    select
        t.*,
        case when min(product) over(partition by customer_account) <> max(product) over(partition by customer_account)
            then 'Dual Product' 
            else concat(product, ' Only')
        end single_or_dual_product
    from mytable t
    

    【讨论】:

      【解决方案2】:
      SELECT t1.*,
             CASE WHEN t2.CustomerAccount IS NOT NULL
                  THEN 'Dual Product'
                  WHEN t1.Product = 'Gas'
                  THEN 'Gas Only'
                  WHEN t1.Product = 'Power'
                  THEN 'Power Only'
                  ELSE 'Wrong product type'
                  END ProductType
      FROM sourcetable t1
      LEFT JOIN sourcetable t2 ON t1.CustomerAccount = t2.CustomerAccount
                              AND t1.Product != t2.Product    
      

      查询不使用ProductID,也不检查它是否匹配CustomerAccount 和/或Product。这将是没有任何利润的多余工作。

      【讨论】:

      • 谢谢,我也一直在考虑入桌。您的解决方案给了我一些重复,我认为是因为加入是在 CustomerAccount 上进行的。有什么方法可以修改它,以便使用产品 ID 连接表?谢谢
      • @Pawel_L ON LEFT(t1.Product, LENGTH(t1.Product) - 1) = LEFT(t2.Product, LENGTH(t2.Product) - 1),例如。
      【解决方案3】:

      你没有提到你使用的是哪个数据库,所以我假设它是 MySQL 8.x。

      使用 CTE 将 IDTYPE 分开可能会更好。然后,查询变得容易得多。例如:

      with
      x as ( -- this CTE just to separate the ID from the TYPE
        select *,
          substring(productid, 1, char_length(productid) - 1) as id,
          right(productid, 1) as type
        from t
      )
      select x.*, case when y.id is null then 'Power Only' else 'Dual' end
      from x
      left join y on x.id = y.id and y.type = 'G'
      where x.type = 'E'
      union all
      select x.*, case when y.id is null then 'Gas Only' else 'Dual' end
      from x
      left join y on x.id = y.id and y.type = 'E'
      where x.type = 'G'
      order by id, type
      

      请注意,我使用UNION ALL。这是因为 MySQL(还)没有实现 FULL OUTER JOIN。这里的技巧是重复查询有点reversed

      【讨论】:

        猜你喜欢
        • 2020-02-24
        • 2021-06-27
        • 1970-01-01
        • 2018-10-12
        • 2021-08-12
        • 2013-04-08
        • 2012-01-26
        • 2022-11-10
        • 1970-01-01
        相关资源
        最近更新 更多