0

我不擅长 sql,所以任何帮助世界都很棒

我有一个 SQL 查询,它获取从一月到本月注册的记录

我的代码示例

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,三月 = 3,四月 = 4,五月 = 5

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

谢谢你。

4

2 回答 2

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
于 2013-06-06T18:23:11.780 回答
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_
于 2013-06-06T17:59:45.530 回答