使用条件计算不同表中的SUM

时间:2011-05-26 11:24:40

标签: sql-server-2005 sum between

我有4个SQL Server 2005表:MainTable,Info,Repairs,Maintenance

MainTable表:

MainID, PlateNo
1, A123
2, D222

信息表:

InfoID, MainID, Location
1, 1, California
2, 2, Ohio

修理表:

RepairID, MainID, Cost, InvoiceNo, InvoiceDate
1, 1, 250, 3423523, 12/10/2010
2, 1, 340, 5634534, 08/11/2010
3, 2, 125, 9258143, 10/02/2010

维护表:

MaintenanceID, MainID, Cost, InvoiceNo, InvoiceDate
1, 1, 223, 9694534, 07/03/2009
2, 2, 830, 4259943, 01/02/2011

所有表都是通过MainTable的MainID链接的。

我希望从每个PlateNo的Info表中的给定'Location'的两个日期(InvoiceDate)之间的维修,SUM(成本)维修中获得SUM(成本)。

2 个答案:

答案 0 :(得分:0)

我会使用派生表来处理此查询。您可以轻松使用公用表表达式。

Select Main.MainId,
       Main.PlateNo,
       Info.Location,
       MaintenanceCosts.MaintenanceCost,
       RepairCosts.RepairCost
From   Main
       Inner Join Info
         On Main.MainId = Info.MainId
       Left Join (
         Select MainId, Sum(Cost) As MaintenanceCost
         From   Maintenance
         Where  InvoiceDate >= @StartDate
                And InvoiceDate < @EndDate
         Group By MainId
         ) As MaintenanceCosts
         On Main.MainId = MaintenanceCosts.MainId
       Left Join (
         Select MainId, Sum(Cost) As RepairCost
         From   Repairs
         Where  InvoiceDate >= @StartDate
                And InvoiceDate < @EndDate
         Group By MainId
         ) As RepairCosts
         On Main.MainId = RepairCosts.MainId
Where  Info.Location = @Location 

答案 1 :(得分:0)

尝试

select 

isnull(sum(a.[ Cost]) + sum(b.[ Cost]),0) cost,
a.[ MainID],a.[ InvoiceDate]

from 

[maintanen] a inner join 
[repairs] b 

on a.[ MainID]=b.[ MainID]


group by a.[ MainID],a.[ InvoiceDate]

COMBINE LOCATION