I have tables Orders, Networks and Users and I need to get total orders count and total sum for orders for every user, and users count in the same network that every user have.
SQLFiddle with sample data: http://sqlfiddle.com/#!9/dcbeea/1
users.userid, orders.id - unique primary keys.
In this example check user #24 row: values for total_orders, total_revenue, network_users are not correct.
Current results for user #24: total_orders: 6, total_revenue: 350, network_users: 6.
Expected results for user #24: total_orders: 3, total_revenue: 175, network_users: 2.
This is SQL request:
SELECT u.*,
count(o.id) AS total_orders,
sum(o.total) AS total_revenue,
count(un.userid) as network_users /* Users count in same network */
FROM users u
LEFT JOIN orders o ON o.userid=u.userid
LEFT JOIN users am ON u.ownerid = am.userid
LEFT JOIN users bdr ON u.bdrid = bdr.userid
LEFT JOIN networks n ON u.networkid = n.networkid
LEFT JOIN users un ON n.networkid=un.networkid
GROUP BY u.userid
ORDER BY u.userid DESC;
ISSUE 1: total_orders and total_revenue here return incorrect values (more than it should, looks like it summed few times because of networks table join).
I can fix total_orders by adding distinct - count(distinct(o.id)) AS total_orders, however this does not work for sum because I can't set to sum total only by disctinct ID's, as I see there is no way to set this in SQL.
You can see issue in SQLFiddle example - user #24 should have total_revenue = 175, however you see it calculated as 350. As I see this happens because two different users associated with the same network (Network #1) that user #24 have.
ISSUE 2: count(un.userid) as network_users - this does not work properly if I don't add count(disctinct(un.userid)) as network_users. Without 'distinct' this show me overall networks count as I see (and not a overall users count in network with the same networkid as current user have). In SQL example 'network_users' for user id #24 should be 2 (because only 2 users in this network), however I see 6 in results.
QUESTION: How to change SQL request to get correct expected mathematically results?