Sql server 如何在SQLServer2005中的select查询中获取记录月总数

Sql server 如何在SQLServer2005中的select查询中获取记录月总数,sql-server,datetime,Sql Server,Datetime,我有以下查询输出 查询: 但是我希望每个n个月记录都有null/0值 如六月和七月记录不可用,则应显示如下所示 Month TotalBreakTime Minute firstName ----- -------------- ------ --------- January 0 0 NULL February 0 0 NULL March

我有以下查询输出

查询:

但是我希望每个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

您应该为月份创建一个虚拟表或子查询,并将其与totals查询连接起来

乙二醇

试试这个:

;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

日历表也有助于写得更干净SQL@podiluska请更正您答案中关于months.monthname=totals.month的以下行
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
;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