查詢postgreSQL 9.4 db,我希望能夠根據以前的訂單查看每個客戶與每個員工進行交互的頻率。我的目標是在下面的格式檢索數據:多個COUNT/GROUP BY語句返回意外結果
CUSTOMER EMPLOYEE INTERACTIONS CUSTOMER_TOTAL
Customer1 EmployeeA 30 50
Customer1 EmployeeB 20 50
Customer2 EmployeeD 6 15
Customer2 EmployeeA 6 15
Customer2 EmployeeC 3 15
...在那裏我有在結果客戶和員工的每一個組合單獨的記錄(假設至少一個訂單已採取了兩者之間的地方) 。
我想包含一個列,其中包含客戶與每位員工之間的訂單數量(請參閱上面的第3列),另一列包含每位客戶的總訂單數量(請參閱上面的第4列)。
我已經寫了下面的查詢:
SELECT customer.name as Customer, employee.name as Employee,
SUM(CASE WHEN orders.employee_id = employee.id AND orders.customer_id = customer.id THEN 1 ELSE 0 END) AS Interactions,
SUM(CASE WHEN orders.customer_id = customer.id THEN 1 ELSE 0 END) AS Customer_Total
FROM tblcustomer customer
JOIN tblorder orders ON orders.customer_id = customer.id
LEFT JOIN tblemployee employee ON employee.id = orders.employee_id
GROUP BY customer.name, employee.name
ORDER BY Customer, Interactions DESC;
哪個返回的結果如下:
CUSTOMER EMPLOYEE INTERACTIONS CUSTOMER_TOTAL
Customer1 EmployeeA 30 30
Customer1 EmployeeB 20 20
Customer2 EmployeeD 6 6
Customer2 EmployeeA 6 6
Customer2 EmployeeC 3 3
所有行/列出現預期,除了最後一列。而不是每個客戶的總訂單數,它只返回僱員也匹配的訂單。我哪裏錯了?
Customer1的CUSTOMER_TOTAL應該是50&對於Customer2應該是15? –
是的,根據頂部的例子。 – Rory