2016-09-28 72 views
0

查詢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 

所有行/列出現預期,除了最後一列。而不是每個客戶的總訂單數,它只返回僱員也匹配的訂單。我哪裏錯了?

+0

Customer1的CUSTOMER_TOTAL應該是50&對於Customer2應該是15? –

+0

是的,根據頂部的例子。 – Rory

回答

0

我想你應該在這裏使用LEFT JOIN

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 
LEFT 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; 

我的直覺是你的INNER JOIN s的過濾掉其中將包括客戶的總記錄。通過使用LEFT JOIN您保留這些記錄。

+0

我用'LEFT JOIN'取代了我的連接,不幸的是同樣的結果。 – Rory

0

一個左加入tblEmployee將執行任務。與tblEmployee的內部聯接將過濾並獲取客戶與每位員工之間訂單數量的記錄。

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; 
+0

我嘗試用'LEFT JOIN'替換我的第二個內部連接,這並沒有影響結果。我也嘗試用'LEFT JOIN'替換兩個連接,但沒有運氣。 – Rory