RoughNeck
RoughNeck

Reputation: 45

SQL Year to Date report involving 3 tables

I am trying to create a year to date report that lists all clients with the totals from all invoices from the current date since the beginning of the year. I also want to join the same total columns from a budgeting table so they are able to compare actual vs budget. I am able to join the clients to the Invoices and get their totals correctly, but I am not able to get the correct values when I join the budgets table.

tbl_Clients
- ID uniqueidentifier
- Name varchar(100)
- isActive bit
- isDeleted bit

tbl_Invoices
-ClientID uniqueidentifier
-Month int
-Year int
-Energy int
-Demand int
-DemandDollar decimal(18,2)
-EnergyDollar decimal(18,2)
-IsActive bit
-IsDeleted bit

tbl_Budgets
-ClientID uniqueidentifier
-Month int
-Year int
-Energy int
-Demand int
-DemandDollar decimal(18,2)
-EnergyDollar decimal(18,2)
-IsActive bit
-IsDeleted bit

This procedure currently works to get each clients totals from tbl_Invoices. I'm just not sure how to then add the tbl_Budgets table totals as 5 more columns. The Mills column from the budget table is calculated in the same fashion.

Here is the procedure I currently have with the static values of 2012 and 9(September) They will eventually be parameters in a stored proc.

Select cli.name
    , Sum(inv.DemandDollar) as DemandDollar
    , SUM(inv.EnergyDollar) as EnergyDollar
    , Sum(inv.Energy) as Energy
    , Sum(inv.Demand) as Demand
    , Mills = 
        (
        case when sum(inv.Energy) = 0
        then 0.00
        else
        Cast((((sum(inv.DemandDollar) + sum(inv.EnergyDollar))/sum(inv.Energy))* 1000) as decimal(18,2))
        end 
        )

from tbl_Clients cli
join tbl_Invoices inv
on inv.ClientID = cli.ID

where cli.IsActive = 1 and cli.IsDeleted = 0 
and inv.IsActive = 1 
and inv.IsDeleted = 0 and inv.Year = 2012 and inv.Month <= 9 
group by cli.name

Upvotes: 0

Views: 245

Answers (1)

Chris Latta
Chris Latta

Reputation: 20560

The first thing you need to ask yourself is whether clients that have no invoices can have budgets and do they need to be included? Also, can clients that have no budgets have invoices? Does every client that has an invoice have a budget and does every client that has a budget have an invoice? The answers to these questions will effect how you structure your query.

So maybe this, which picks up all budgets and invoices regardless:

SELECT cli.Name, SUM(UsedDollar) AS UsedDollar, SUM(BudgetDollar) AS BudgetDollar
(SELECT ClientID, EnergyDollar AS UsedDollar, 0.0 AS BudgetDollar
FROM tbl_Invoices
WHERE Year = 2012 AND Month <= 9
UNION ALL
SELECT ClientID, 0.0 AS UsedDollar, EnergyDollar AS BudgetDollar
FROM tbl_Budgets
WHERE Year = 2012 AND Month <= 9
) DT 
INNER JOIN tbl_Clients cli ON DT.ClientID = cli.ID
GROUP BY cli.Name

Upvotes: 1

Related Questions