如何合并具有相似值的两行?

时间:2019-05-20 14:36:43

标签: sql

这可能是一个非常基本的问题,但我似乎无法弄清楚。我有以下查询:

SELECT COUNT(wp_woocommerce_order_itemmeta.meta_key) as Aantal, wp_woocommerce_order_itemmeta.meta_value as Formule FROM wp_woocommerce_order_itemmeta 
LEFT JOIN wp_woocommerce_order_items 
ON wp_woocommerce_order_itemmeta.order_item_id = wp_woocommerce_order_items.order_item_id
LEFT JOIN wp_posts
ON wp_woocommerce_order_items.order_id = wp_posts.ID
WHERE wp_woocommerce_order_itemmeta.meta_key = 'pa_formule'
GROUP BY wp_woocommerce_order_itemmeta.meta_value
HAVING COUNT(wp_woocommerce_order_itemmeta.meta_key) > 10

哪个返回与此类似的表:

3305   all-in-one
5454   curling
1200   length-define
800    length-define-2
920    define-length

我想结合相似的“ Formule”值(底部3个)来创建下表:

3305   all-in-one
5454   curling
2920   length-define

我发现大多数答案仅适用于group by,但要求“ Formule”的值相同,但在这种情况下,它们不是相同的。谢谢!

1 个答案:

答案 0 :(得分:1)

使用case表达式定义您要通过其进行汇总的列:

SELECT COUNT(woim.meta_key) as Aantal,
       (CASE WHEN woim.meta_value IN ('length-define', 'length-define-2', 'define-length') THEN 'length-define'
             ELSE woim.meta_value
        END) as Formule
FROM wp_woocommerce_order_itemmeta  woi mLEFT JOIN
     wp_woocommerce_order_items woi
     ON woim.order_item_id = woi.order_item_id LEFT JOIN
     wp_posts p
     ON woi.order_id = p.ID
WHERE woim.meta_key = 'pa_formule'
GROUP BY Formule
HAVING COUNT(woim.meta_key) > 10;

并非所有数据库都支持GROUP BY中的列别名。如果不是,则需要重复CASE表达式。