Skip to content
Advertisement

How to use SQL math functions with multiple joins

in SQL Server I have two fact tables. FactA I will use COUNT(DISTINCT) and need to use two joins to get the needed GROUP BY and WHERE data from DimB. FactB uses SUM and needs only one join to DimB. Now I can make these queries work one by one, but I am at complete lost, trying to merge them into one query.

Here is an extremely simplified example data:

Example queries that work by themselves and give expected results are:

I need to combine these two, so I can get the results with one query, and use GROUP BY and WHERE clause from DimB. I tried this:

And it failed miserably, because it is giving way too large numbers in TotalSales. I believe it is summing way too much sales, because of the many joins. Searching around I belive subqueries might be the answer, but I am overwhelmed about which part I should be subquerying. Many thanks to anyone who has time to help.

Advertisement

Answer

I’m going to guess these are the results you want. Please always state the desired results explicitly so we don’t have to guess.

Results:

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement