从几个事实表中获取维度记录的SUM

时间:2014-09-05 09:06:46

标签: sql sql-server sql-server-2012

我必须在下面查询2个计算正确值的查询:

Select Finances.CustomerID,
sum(Finances.Total)Total
from Finances
group by Finances.CustomerID
order by Finances.CustomerID

Select Invoices.CustomerID,
sum(Invoices.InvoiceValue)InvoiceValue
from Invoices
group by Invoices.CustomerID
order by Invoices.CustomerID
在财务表格中,客户可以从多个订单中欠款,因此对于这个例子,我们可以说客户必须支付100英镑+ 400英镑+ 500英镑,总计1000英镑。

然后客户收到100英镑的第一张发票,并支付此费用。

所以第二个查询现在显示100英镑....从这两个值我然后想要计算第三列,从1000英镑中扣除100英镑等于900英镑(剩余金额)

是我的表结构:

enter image description here

还有更多的表关联,但这是我使用select语句的数据:)

我如何编写sql语句来完成所有这些或者不可能?理想情况下,我希望在INSERT中使用 - >选择 - > WHERE NOT EXISTS语句或者在视图中填充。谢谢你的帮助

示例数据: enter image description here

2 个答案:

答案 0 :(得分:3)

CREATE VIEW CustomerFinances AS
    ;WITH FinancesCTE AS
    (
        Select Finances.CustomerID,
        sum(Finances.Total)Total
        from Finances
        group by Finances.CustomerID
    ),InvoicesCTE AS
    (
        Select Invoices.CustomerID,
        sum(Invoices.InvoiceValue)InvoiceValue
        from Invoices
        group by Invoices.CustomerID
    )
    SELECT C.*,
           F.Total AS FinanceTotal,
           I.InvoiceValue
    FROM   Customers C
           LEFT JOIN FinancesCTE F
               ON C.CustomerID = F.CustomerID
           LEFT JOIN InvoicesCTE I
               ON C.CustomerID = I.CustomerID

GO

答案 1 :(得分:1)

试试这个,

CREATE VIEW CustomerFinanceDetails AS 
(

 select c.*,isnull(FinanceTotal,0) as FinanceTotal,isnull(InvoiceTotal,0) as InvoiceTotal 
 from 
 (select * from Customers) c
   left outer join 
 (select CustomerID,isnull(SUM(Total),0) as FinanceTotal from Finances group by CustomerID) f on c.CustumerID=f.CustomerID
   left outer join 
 (select CustomerID,isnull(SUM(InvoiceValue),0) as InvoiceTotal from Invoices group by CustomerID) i on c.CustumerID= i.CustomerID

)