从group on date字段动态创建缺少的月份

时间:2015-05-27 14:21:02

标签: sql sql-server tsql sql-server-2014

在下面的SQL中,我试图插入行来填充结果中缺少的月份。由于帖子SQL select, pad with chronological missing months

,解决方案非常接近

但是这段代码运行gr8但仍然缺少几个月,问题是如何加入/联合临时表

DECLARE @StartDate DATETIME = dateadd(m,-12,getdate()), @EndDate DATETIME = getdate(), @DATE DATETIME

DECLARE @TEMP AS TABLE (MeterReadDate datetime)

SET @DATE = @StartDate

WHILE @DATE <= @EndDate
BEGIN
     INSERT INTO @TEMP VALUES ( @DATE)
    SET @DATE = DATEADD(MONTH,1,@DATE)
END



SELECT convert(char(7), t.MeterReadDate, 121),count(*)

  FROM @TEMP m left join
     [PremiseMeterReadProviders] t
     on convert(char(7), t.MeterReadDate, 121) = convert(char(7), m.MeterReadDate, 121)

  where (t.MeterReadDate > dateadd(m,-12,getdate()))
  group by  convert(char(7), t.MeterReadDate, 121)
  order by  convert(char(7), t.MeterReadDate, 121)

2 个答案:

答案 0 :(得分:0)

尝试这样的事情......

;WITH Months AS 
(
 SELECT TOP 12 
   CONVERT(CHAR(7),
       DATEADD(MONTH 
               , - ROW_NUMBER() OVER (ORDER BY (SELECT NULL))
               , GETDATE()
               )
           ,121) MonthNo
 FROM master..spt_values
 )
SELECT convert(char(7), t.MeterReadDate, 121),count(*)
FROM Months m
LEFT JOIN  [PremiseMeterReadProviders] t
      ON convert(char(7), t.MeterReadDate, 121) = m.MonthNo
     AND (t.MeterReadDate > dateadd(m,-12,getdate()))
group by  convert(char(7), t.MeterReadDate, 121)
order by  convert(char(7), t.MeterReadDate, 121)

答案 1 :(得分:0)

我认为您需要重建查询,如下所示

DECLARE @StartDate DATETIME = dateadd(m,-12,getdate()), @EndDate DATETIME = getdate(), @DATE DATETIME

DECLARE @TEMP AS TABLE (MeterReadDate datetime)

SET @DATE = @StartDate

WHILE @DATE <= @EndDate
BEGIN
     INSERT INTO @TEMP VALUES ( @DATE)
    SET @DATE = DATEADD(MONTH,1,@DATE)
END



SELECT convert(char(7), m.MeterReadDate, 121),count(*)

  FROM @TEMP m left join
     [Announcement] t
     on convert(char(7), t.ExpiryDate, 121) = convert(char(7), m.MeterReadDate, 121)

  WHERE (t.ExpiryDate IS NULL OR t.ExpiryDate > dateadd(m,-12,getdate()))
  group by  convert(char(7), m.MeterReadDate, 121)
  order by  convert(char(7), m.MeterReadDate, 121)

在where条件中,我添加了t.ExpiryDate IS NULL,因为这对于缺少的月份将为null。