sql查询获取从Jan到当月的所有数据,即使没有记录

时间:2013-06-06 17:49:41

标签: sql sql-server

我对sql不好,所以任何帮助世界都很棒

我有一个SQL查询,可以获取从Jan到当月注册的记录

我的代码示例

SELECT DatePart(YEAR, p.createStamp) as TheYear, DatePart(MONTH, p.createStamp) as TheMonth ,  COUNT(p.pId) AS TOTALCOUNT 
FROM profile p with(nolock)
where DatePart(YEAR, p.createStamp) = DATEPART(YEAR, GETDATE())
GROUP BY YEAR(p.createStamp), MONTH(p.createStamp)
ORDER BY YEAR(p.createStamp), MONTH(p.createStamp)

查询将如何恢复

2月= 2,3月= 3,4月= 4,5月= 5

我想让它带回Jan = 1,总计数为0,June = 6,总计数为0,以及任何想法如何做到这一点?

谢谢。

2 个答案:

答案 0 :(得分:1)

这是一个创建月/年组合的循环,并将其用作查询的基础:

declare @startDate as datetime
set @startDate = '1/1/13'

declare @currentDate as datetime
set @currentDate = '6/6/13'

select
     month(@currentDate) as monthOfDate
    ,year(@currentDate) as yearOfDate
into #allDates
where 1=0

while (@startDate <= @currentDate)
begin
    insert into #allDates values (month(@startDate),year(@startDate))
    set @startDate = dateadd(m,1,@startDate)
end

select 
     _monthYear.yearofDate
    ,_monthYear.monthOfDate
    , COUNT(p.pId) as total
from #allDates _monthYear
left join profile p with(nolock)
    on month(p.createStamp) = _monthYear.monthOfDate
    and year(p.createStamp) = _monthYear.yearOfDate
group by
     _monthYear.yearofDate
    ,_monthYear.montOfDate

drop table #allDates

答案 1 :(得分:0)

您无法选择不存在的内容,因此我建议您创建一个查找表:

CREATE TABLE #Months (Year_ INT, Month_ INT)
GO
SET NOCOUNT ON
DECLARE @intFlag INT
SET @intFlag = 1
WHILE (@intFlag <=20)
BEGIN
--Do Stuff
INSERT INTO #Months
SELECT YEAR(DATEADD(MONTH,@intflag,'20121201')),MONTH(DATEADD(MONTH,@intflag,'20121201'))
SET @intFlag = @intFlag + 1
END
GO

您可以将“20”更改为您想要的任意月份,并将两个位置中的“20121201”更改为您要开始查找的月份之前的月份。

然后加入该表,我相信以下内容将起作用:

SELECT m.Year_ as TheYear, m.Month_ as TheMonth ,  ISNULL(COUNT(p.pId),0) AS TOTALCOUNT 
FROM profile p
RIGHT JOIN #Months m
ON DatePart(YEAR, p.createStamp) = m.Year_
AND  DatePart(MONTH, p.createStamp) = m.Month_
where DatePart(YEAR, p.createStamp) = DATEPART(YEAR, GETDATE())
GROUP BY m.Year_, m.Month_
ORDER BY  m.Year_, m.Month_