我的SQL語法如下
SELECT ps_customer.id_customer,
COUNT(ps_orders.id_order) AS pef,
0 AS pin
FROM ps_customer
LEFT JOIN ps_orders ON ps_orders.id_customer=ps_customer.id_customer WHERE (ps_orders.id_order IS NULL OR ps_customer.id_customer IN (SELECT id_customer FROM ps_orders) AND valid = 1)
AND siret IS NOT NULL AND mobile IS NOT NULL AND mobile != '' AND active=1
AND date_format(ps_customer.date_add,'%Y-%m')<date_format(DATE_SUB(curdate(), INTERVAL 2 MONTH),'%Y-%m')
AND ps_customer.id_customer = 88
UNION
SELECT ps_customer.id_customer,
0 AS pef,
COUNT(ps_orders.id_order) AS pin
FROM ps_customer
LEFT JOIN ps_orders ON ps_orders.id_customer=ps_customer.id_customer
WHERE (ps_orders.id_order IS NULL OR ps_customer.id_customer IN (SELECT id_customer FROM ps_orders) AND valid = 0)
AND siret IS NOT NULL AND mobile IS NOT NULL AND mobile != '' AND active=1
AND date_format(ps_customer.date_add,'%Y-%m')<date_format(DATE_SUB(curdate(), INTERVAL 2 MONTH),'%Y-%m')
AND ps_customer.id_customer = 88;
撈出結果如下
我現在撈出2筆結果那我想要把重複的值合併成一筆結果,我該怎麼下語法呢?我研究很久都沒有解答,不知道各位前輩有什麼好辦法可以給小弟指點一下迷津,感激不盡!!!!
大大好這是我預期的結果就是那個pin欄位值5跟pef欄位值20在同一筆結果裡面
如我留言那樣,最快解決你目前問題可以使用 Subquery with sum
但我覺得你的語法可以更進一步優化,如果提供原始樣本資料 我覺得可以寫出效能更好更漂亮的語法
SELECT id_customer,sum(pef),sum(pin)
FROM (
SELECT ps_customer.id_customer,
COUNT(ps_orders.id_order) AS pef,
0 AS pin
FROM ps_customer
LEFT JOIN ps_orders ON ps_orders.id_customer=ps_customer.id_customer WHERE (ps_orders.id_order IS NULL OR ps_customer.id_customer IN (SELECT id_customer FROM ps_orders) AND valid = 1)
AND siret IS NOT NULL AND mobile IS NOT NULL AND mobile != '' AND active=1
AND date_format(ps_customer.date_add,'%Y-%m')<date_format(DATE_SUB(curdate(), INTERVAL 2 MONTH),'%Y-%m')
AND ps_customer.id_customer = 88
UNION
SELECT ps_customer.id_customer,
0 AS pef,
COUNT(ps_orders.id_order) AS pin
FROM ps_customer
LEFT JOIN ps_orders ON ps_orders.id_customer=ps_customer.id_customer
WHERE (ps_orders.id_order IS NULL OR ps_customer.id_customer IN (SELECT id_customer FROM ps_orders) AND valid = 0)
AND siret IS NOT NULL AND mobile IS NOT NULL AND mobile != '' AND active=1
AND date_format(ps_customer.date_add,'%Y-%m')<date_format(DATE_SUB(curdate(), INTERVAL 2 MONTH),'%Y-%m')
AND ps_customer.id_customer = 88
)t1
GROUP BY id_customer