0

我有以下查询输出

在此处输入图像描述

询问:

SELECT DATENAME(mm, date) [Month], sum(braekTime) [TotalBreakTime],
sum(DATEPART(hh,totalTime) * 60 + DATEPART(mi,totalTime) + DATEPART(ss,totalTime) * 0.017) [Minute],firstName
    FROM employeeAttendance,employee
    where FK_employeeId = employee.employeeId
    GROUP BY DATENAME(mm, date),firstName
    ORDER BY [Month]

我希望每个月的每个 n 记录都具有 null/0 值 ,例如六月和七月的记录不可用,那么它应该显示如下

Month    TotalBreakTime   Minute   firstName    
-----    --------------   ------    ---------
January       0           0           NULL
February      0           0           NULL
March         0           0           NULL
April         0           0           NULL
May           50          1015.000    foramaa 
June          0            0          NULL
July          0            0          NULL     
 .... Like till Dec
4

2 回答 2

0

您应该为月份创建一个虚拟表或子查询,并将其加入到总计查询中。

例如

select * from
(
    select number, datename(m,DATEADD(m, number-1, 0)) as monthname 
    from master..spt_values 
    where type='p' and number between 1 and 12
) months
    left join
(your totals query) totals
    on months.monthname = totals.month
于 2012-10-15T10:38:47.843 回答
0

试试这个:

;with cte as(
select 1 as rn union all select 2 union all select 3),
 cte1 as (select ROW_NUMBER() over(order by c1.rn) as row_num
from cte cross join cte c1 cross join cte c2)
select * from cte1
left join
(SELECT DATENAME(mm, date) [Month], 
       sum(braekTime) [TotalBreakTime],
       sum(DATEPART(hh,totalTime) * 60 + DATEPART(mi,totalTime) + DATEPART(ss,totalTime) * 0.017) [Minute],
       firstName
FROM employeeAttendance join employee
on FK_employeeId = employee.employeeId
GROUP BY DATENAME(mm, date),firstName
ORDER BY [Month])B
on B.[Month]=DateName( month , DateAdd( month ,cte1.row_num , 0 ) - 1 )
and cte1.row_num <=12
于 2012-10-15T10:54:34.107 回答