![]() |
[SQL] Performing a distinct count AND taking a sum..
The following query simply takes each user from the users table and gets the visitor count (joined w/ user ID), transaction count (joined w/ user ID), and finally, the sum of all transaction amounts for that user ID.
The problem I'm having is that the query gets the distinct counts just fine for the visitors and transactions, but when I try to sum the "Amount", it ends up multiplying it by the Visitor count. I'm not actually Grouping By the Visitor ID, so where does it get the idea that it should multiply the two together? Example: Code:
SELECT Code:
UserID UserName Visitors Trans Amount Code:
UserID UserName Visitors Trans Amount Code:
UserID UserName I could get around it by changing the amount to be computed like: Code:
SUM(dbo.Trans.Amount)/COUNT(DISTINCT dbo.Visitors.VisitorID) AS Amount Any ideas? Your help is greatly appreciated :D |
check out the compute clause
|
Re: [SQL] Performing a distinct count AND taking a sum..
Quote:
Most likely, you can use SUM(DISTINCT dbo.Trans.Amount). Alternatively, it may be better to include the Visitors part as a subquery, instead of JOINing it: Code:
SELECT Users.UserID, Users.UserName, (SELECT COUNT(Visitors.VisitorID) FROM Visitors WHERE Visitors.UserID = Users.UserID), COUNT(Trans.TransID), SUM(Trans.Amount) |
All times are GMT -8. The time now is 10:25 AM. |
Powered by vBulletin® Version 3.8.7
Copyright ©2000 - 2025, vBulletin Solutions, Inc.
Search Engine Optimization by vBSEO 3.6.0 PL2
© 2002-2012 Tilted Forum Project