如何在Sql Server中将三个表与聚合函数组合在一起

时间:2017-10-25 23:27:18

标签: sql-server

我有三个表,一个是SaleinfoTB,第二个表是StarReadingEndReading,第三个表是SaleinfoTB表中的ExpenseinfoTb我想要总和TotalBill Column和StartReadingEndReading表我想要总结ActualSell列和Plus来自ExpenseintoTB表的列数和总和< / p>

选择SUM((SaleinfoTB.TotalBill)+ SUM(StartReadingEndReading.ActualSell)) -

来自SaleinfoTB,SaleinfoTB,ExpenseinfoTB的

(SUM(ExpenseinfoTB.Amount))

其中SaleinfoTB.Date = StartReadingEndReading.ReadingDate

和ExpenseinfoTB.ExpenseDate = SaleinfoTB.Date

和ExpenseinfoTB.ExpenseDate = StartReadingEndReading.ReadingDate

1 个答案:

答案 0 :(得分:0)

我认为你得到的是如何在进行加/减之前得到每个项目的总和

SELECT (ISNULL(SaleinfoTB.SumTotalBill,0) 
    + ISNULL(StartReadingEndReading.SumActualSell,0)) 
    - ISNULL(ExpenseinfoTB.SumAmount,0)
FROM
    (SELECT SUM(TotalBill) SumTotalBill, [Date] 
            FROM SaleinfoTB  
            Group By [Date])SaleinfoTB
    INNER JOIN 
    (SELECT SUM(ActualSell) SumActualSell, ReadingDate 
            FROM StartReadingEndReading  
            Group By ReadingDate)StartReadingEndReading
        ON SaleinfoTB.[Date]=StartReadingEndReading.ReadingDate
    INNER JOIN
    (SELECT SUM(Amount) SumAmount, ExpenseDate 
            FROM ExpenseinfoTB  
            Group By ExpenseDate)ExpenseinfoTB
        ON ExpenseinfoTB.ExpenseDate=SaleinfoTB.[Date]