按月分组,包含多个表和日期字段

时间:2014-04-30 16:03:49

标签: sql group-by

美好的一天

我需要编写一个涉及3个表的查询。每个表都有一个日期字段。我想运行查询按月分组数据,例如

月度Costtotal Repairtotal Servicetotal

1243年12月2344 123123

3123 213123 21312

每列都来自另一个有自己日期的表。 Costtotal已经购买,repairtotal已经修复并且servicetotal已经服务

提前致谢

1 个答案:

答案 0 :(得分:0)

select
    t.[Month]
    ,sum(t.Costtotal)
    ,sum(t.Repairtotal)
    ,sum(t.Servicetotal)
from 
(
    select
        Datepart(MM, PurchaseDate) as [Month],
        Costtotal,
        0 as Repairtotal,
        0 as Servicetotal
    from tablea

    union

    select
        Datepart(MM, RepairDate) as [Month],
        0 as Costtotal,
        Repairtotal,
        0 as Servicetotal
    from tableb

    union

    select
        Datepart(MM, ServiceDate) as [Month],
        0 as Costtotal,
        0 as Repairtotal,
        Servicetotal
    from tableb
) as t
group by t.[Month]
order by t.[Month]