标签:
传入参数:
@Type:类型,是哪一种报表,有year,month,day三种
@Time:时间
根据Type参数分别获取Time的月份数据,日期数据
declare @Type nvarchar(20) =‘month‘; declare @Time DateTime =getdate(); SELECT distinct CASE WHEN @Type = ‘quarter‘ THEN CONCAT(DATEPART(qq,DATEADD(qq,number,@Time)),‘季度‘) WHEN @Type = ‘month‘ THEN FORMAT(DATEADD(mm,number,@Time),‘MM月‘) ELSE FORMAT(DATEADD(dd,number,@Time),‘dd日‘) END DT FROM master..spt_values WHERE type=‘P‘
先查出这个,然后与数据库中表left join
declare @Type nvarchar(20) =‘month‘; declare @Time DateTime =getdate(); select case @Type when ‘year‘ then format(CreateTime,‘MM月‘) when ‘month‘ then format(CreateTime,‘dd日‘) else format(CreateTime,‘dd日‘) end DT2,Sum ( isnull(ElectricalLaborHour,0)+ isnull(ElectricalParts,0)+ isnull(SheetSprayLaborHour,0)+ isnull(SheetSprayParts,0)+ isnull(SheetSprayTransLaborHour,0)+ isnull(OilChangeLaborHour,0)+ isnull(OilChangeParts,0)+ isnull(WarrantyLaborHour,0)+ isnull(WarrantyParts,0)+ isnull(WarrantyTransLaborHour,0)+ isnull(InternalElectricalLaborHour,0)+ isnull(InternalParts,0)+ isnull(InternalSheetSprayLaborHour,0)) as Total from T_DMSMaintenance where IsDelete=0 and ((@Type=‘year‘ and datepart(yyyy,CreateTime)=datepart(yyyy,@Time)) or (@Type=‘month‘ and format(CreateTime,‘yyyy年MM月‘)=format(@Time,‘yyyy年MM月‘)) or (@Type=‘day‘ and format(CreateTime,‘yyyy-MM-dd‘)=format(@Time,‘yyyy-MM-dd‘))) group by case @Type when ‘year‘ then format(CreateTime,‘MM月‘) when ‘month‘ then format(CreateTime,‘dd日‘) else format(CreateTime,‘dd日‘) end
看上面的查询条件
or,and联合使用,并且根据具体的Type参数进行分组
然后再将两个表进行连接
declare @Type nvarchar(20) =‘month‘; declare @Time DateTime =getdate(); select DT,Total from (SELECT distinct case @Type when ‘year‘ then format(dateadd(mm,number,@Time),‘MM月‘) when ‘month‘ then format(dateadd(dd,number,@Time),‘dd日‘) else format(dateadd(dd,number,@Time),‘dd日‘) end DT FROM master..spt_values WHERE type=‘P‘) as T1 left join (select case @Type when ‘year‘ then format(CreateTime,‘MM月‘) when ‘month‘ then format(CreateTime,‘dd日‘) else format(CreateTime,‘dd日‘) end DT2,Sum ( isnull(ElectricalLaborHour,0)+ isnull(ElectricalParts,0)+ isnull(SheetSprayLaborHour,0)+ isnull(SheetSprayParts,0)+ isnull(SheetSprayTransLaborHour,0)+ isnull(OilChangeLaborHour,0)+ isnull(OilChangeParts,0)+ isnull(WarrantyLaborHour,0)+ isnull(WarrantyParts,0)+ isnull(WarrantyTransLaborHour,0)+ isnull(InternalElectricalLaborHour,0)+ isnull(InternalParts,0)+ isnull(InternalSheetSprayLaborHour,0)) as Total from T_DMSMaintenance where IsDelete=0 and ((@Type=‘year‘ and datepart(yyyy,CreateTime)=datepart(yyyy,@Time)) or (@Type=‘month‘ and format(CreateTime,‘yyyy年MM月‘)=format(@Time,‘yyyy年MM月‘)) or (@Type=‘day‘ and format(CreateTime,‘yyyy-MM-dd‘)=format(@Time,‘yyyy-MM-dd‘))) group by case @Type when ‘year‘ then format(CreateTime,‘MM月‘) when ‘month‘ then format(CreateTime,‘dd日‘) else format(CreateTime,‘dd日‘) end) as T2 on T1.DT=T2.DT2
标签:
原文地址:http://www.cnblogs.com/hongdada/p/4818741.html