0

我有 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 的信息表中获取给定“位置”的两个日期(InvoiceDate)之间的维修总和(成本),维护总和(成本)。

4

2 回答 2

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 
于 2011-05-26T12:41:10.463 回答
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]

结合位置

于 2011-05-27T10:30:53.333 回答