SQL重新组合仅选择的记录

时间:2017-03-01 12:37:46

标签: mysql sql mariadb

我有一个名为chart的数字为0的列,并且需要与product_attribute_id进行分组,因为它是0(如果记录为0,则重新组合为列名{{ 1}})

我不能做GROUP BY,因为我的其他记录将会消失。它只需要在我的product_id中有product_id的记录product_attribute_id与我的另一个名为0的表

进行分组
product_id

enter image description here

我的其他记录只需保留SELECT od.id_order_detail, od.id_order, od.product_id, od.product_attribute_id, od.product_name, (od.product_quantity) AS 'Total closed' FROM ex.ps_order_detail od WHERE od.product_id IN (SELECT DISTINCT p.id_product FROM ex.ps_product p WHERE p.id_manufacturer = '1') ORDER BY od.product_attribute_id , od.product_id DESC 需要与其他列进行协商的记录

1 个答案:

答案 0 :(得分:0)

您可以使用聚合。目前还不清楚你想要的许多列的组合行。这是一个猜测:

SELECT MAX(od.id_order_detail) as id_order_detail,
       MAX(od.id_order) as id_order,
       (CASE WHEN product_attribute_id > 0 THEN product_attribute_id END) as product_attribute_id, 
       MAX(od.product_attribute_id) as product_attribute_id, 
       od.product_name,
       SUM(od.product_quantity) AS TotalClosed
FROM ex.ps_order_detail od
WHERE od.product_id IN (SELECT p.id_product
                        FROM ex.ps_product p
                        WHERE p.id_manufacturer = 1  -- ids are probably  not strings
                       ) 
GROUP BY product_id, product_name,
         (CASE WHEN product_attribute_id > 0 THEN product_attribute_id END)
ORDER BY product_attribute_id, product_id DESC;