0

我正在尝试创建一个年初至今的报告,其中列出了所有客户以及自年初以来当前日期的所有发票的总数。我还想从预算表中加入相同的总列,以便他们能够比较实际与预算。我能够将客户加入发票并正确获得他们的总数,但是当我加入预算表时我无法获得正确的值。

tbl_Clients
- ID 唯一标识符
- 名称 varchar(100)
- isActive 位
- isDeleted 位

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

此过程当前用于从 tbl_Invoices 获取每个客户的总数。我只是不确定如何将 tbl_Budgets 表总计添加为 5 列。预算表中的 Mills 列以相同的方式计算。

这是我目前使用的静态值 2012 和 9(9 月)的过程它们最终将成为存储过程中的参数。

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
4

1 回答 1

1

您需要问自己的第一件事是,没有发票的客户是否可以有预算,是否需要包括在内?另外,没有预算的客户可以有发票吗?是否每个有发票的客户都有预算,是否每个有预算的客户都有发票?这些问题的答案将影响您构建查询的方式。

所以也许这个,它拿起所有的预算和发票,不管:

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
于 2012-12-07T02:42:31.457 回答