2017-03-01 134 views
0

我有1列編號爲0稱爲product_attribute_id和一個需要組product_id,因爲它是0(東西一樣,如果記錄爲0,則與列名重整旗鼓product_idSQL重新組合只選擇記錄

我可以」只是做GROUP BY,因爲我的其他記錄將會消失。它只需要組時,我product_attribute_id有記錄0在它與我的叫product_id

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 

enter image description here

我的其他記錄需要留只0需要記錄與另一列

到Groep的其它表
+1

添加示例表數據和預期結果 - 以及格式化文本! – jarlh

+0

你正在使用哪些DBMS?您的列別名是無效的標準SQL。 –

+0

我正在使用MariaDB – Deniz

回答

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;