Here's a simplified version of the problem:
There are four tables: order, user, group, user_group.
The order table has a user_id field indicating which user created the order, and a quantity field--order_qty.
A user can belong to multiple groups via an entry in the user_group table.
The group table has a field--group_type--which indicates whether group members are company employees or not.
How can a query be constructed which sums order_qty for orders made by employees.
Here's what I have so far, but it includes records more than once when a user belongs to more than one employee group:
SELECT field1, field2, SUM(order_qty)
FROM order
JOIN user_group
ON order.user_id = user_group.user_id
JOIN group
ON user_group.group_id = group.group_id
AND group.group_type = 'employee'
GROUP BY field1, field2
There are four tables: order, user, group, user_group.
The order table has a user_id field indicating which user created the order, and a quantity field--order_qty.
A user can belong to multiple groups via an entry in the user_group table.
The group table has a field--group_type--which indicates whether group members are company employees or not.
How can a query be constructed which sums order_qty for orders made by employees.
Here's what I have so far, but it includes records more than once when a user belongs to more than one employee group:
SELECT field1, field2, SUM(order_qty)
FROM order
JOIN user_group
ON order.user_id = user_group.user_id
JOIN group
ON user_group.group_id = group.group_id
AND group.group_type = 'employee'
GROUP BY field1, field2