根据条件

计算不同表的SUM。 我有4个SQL Server 2005表:MainTable,Info,维修,维护 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链接。 我想在两个日期(InvoiceDate)之间为每个PlateNo从信息表中给定的“位置”,从维修中获得SUM(费用),从维护中获得SUM(费用)。     
已邀请:
我将使用派生表来处理此查询。您可以轻松地使用通用表表达式。
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 
    
尝试这个
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]
组合位置     

要回复问题请先登录注册