UNIONing這將是相當簡單的,但不知道它會給你有用的值
SELECT a.id, a.branch_code, SUM(c.amount) AS AmountSum, d.category, e.branch_commission
FROM control_panel_client_create AS a
RIGHT JOIN sales_add_h AS b ON a.id = b.branch_code_id
RIGHT JOIN sales_add_i AS c ON b.id = c.sales_h_id
RIGHT JOIN control_panel_item_create AS d ON c.item_code_id = d.id
INNER JOIN control_panel_client_create AS e ON b.branch_code_id = e.id
WHERE c.transac_type = 0
GROUP BY d.category, b.branch_code_id
UNION
SELECT a.id, a.branch_code, SUM(c.amount) AS AmountSum, d.category, e.branch_commission
FROM control_panel_client_create AS a
RIGHT JOIN sales_add_h AS b ON a.id = b.branch_code_id
RIGHT JOIN sales_add_i AS c ON b.id = c.sales_h_id
RIGHT JOIN control_panel_item_create AS d ON c.item_code_id = d.id
INNER JOIN control_panel_client_create AS e ON b.branch_code_id = e.id
WHERE c.transac_type = 1
GROUP BY d.category, b.branch_code_id
ORDER BY AmountSum DESC
你可以只讓和兩個TRANSAC類型
SELECT a.id, a.branch_code, SUM(c.amount) AS AmountSum, d.category, e.branch_commission
FROM control_panel_client_create AS a
RIGHT JOIN sales_add_h AS b ON a.id = b.branch_code_id
RIGHT JOIN sales_add_i AS c ON b.id = c.sales_h_id
RIGHT JOIN control_panel_item_create AS d ON c.item_code_id = d.id
INNER JOIN control_panel_client_create AS e ON b.branch_code_id = e.id
WHERE c.transac_type IN (0, 1)
GROUP BY d.category, b.branch_code_id
ORDER BY AmountSum DESC
或者總和對於兩者分開
SELECT a.id, a.branch_code, SUM(c.amount) AS AmountSum, d.category, e.branch_commission , c.transac_type
FROM control_panel_client_create AS a
RIGHT JOIN sales_add_h AS b ON a.id = b.branch_code_id
RIGHT JOIN sales_add_i AS c ON b.id = c.sales_h_id
RIGHT JOIN control_panel_item_create AS d ON c.item_code_id = d.id
INNER JOIN control_panel_client_create AS e ON b.branch_code_id = e.id
WHERE c.transac_type IN (0, 1)
GROUP BY d.category, b.branch_code_id, c.transac_type
ORDER BY AmountSum DESC
把這兩方面都在同一條線上的
討厭的方式: -
SELECT a.id, a.branch_code, SUM(IF(c.transac_type=0,c.amount, 0)) AS AmountSumTransac_0, SUM(IF(c.transac_type=1, c.amount, 0)) AS AmountSumTransac_1, d.category, e.branch_commission
FROM control_panel_client_create AS a
RIGHT JOIN sales_add_h AS b ON a.id = b.branch_code_id
RIGHT JOIN sales_add_i AS c ON b.id = c.sales_h_id
RIGHT JOIN control_panel_item_create AS d ON c.item_code_id = d.id
INNER JOIN control_panel_client_create AS e ON b.branch_code_id = e.id
WHERE c.transac_type IN (0, 1)
GROUP BY d.category, b.branch_code_id
ORDER BY AmountSum DESC
爲什麼不'WHERE c.transac_type IN( 0,1)'而不是'UNION'? –
mysqli在這裏是一個錯誤的標籤 –
只是FYI,術語'[mysql]和'正確加入''目前出現在SO 952次。與出現22935次的[mysql]和「left join」相比...我只是說。 – Strawberry