T-SQL - Insert Missing Data for Specific Period of Time

时间:2018-04-18 18:06:50

标签: sql tsql bigdata relational-database

I am having trouble solving this problem with missing data for 4/13-4/15. See screenshot: Daily Subscriber Counts

This screenshot was produced by [Edit: Part Of] the following code:

SELECT  
    MIN([AsOfDate]) AS StartDate,
    MAX([AsOfDate]) AS EndDate,
    SUM([TotalCustomers]) AS TotalSubs,
    SUM([HSDCustomers]) AS HSDSubs,
    SUM([PhoneCustomers]) AS PhoneSubs,
    SUM([VideoCustomers]) AS VideoSubs
FROM 
    [vDailyCustomerCounts]
WHERE
    Sourcesystem = 'ICOMS'
    AND (Asofdate BETWEEN '4/8/2018' AND '4/18/2018')
    AND iscommercial = 0
GROUP BY 
    [AsOfDate]
ORDER BY 
    [AsOfDate] DESC

Essentially my issue is that I need to insert "dummy" data into the select statement. I need to create a row for 2018-04-13 through 2018-04-15 and populate it with either a general count (like 502,900) or use the previous day's count.

Ideally, I want to create something like below:

StartDate   End Date     TotalSubs
----------------------------------
2018-04-13  2018-04-13   502900

I only want to insert this dummy data if a missing day occurs in the data set. I would greatly appreciate any help!

2 个答案:

答案 0 :(得分:0)

请参阅此网页:ActionDispatch::Cookies

如果存在不合需要的值,您可以在SELECT语句中使用CASE来选择虚拟值。

答案 1 :(得分:0)

使用这样的循环首先填写您缺少的日期 - 然后添加默认值并继续进行汇总

  declare @mindate datetime=(select min(Asofdate) from vDailyCustomerCounts)
  declare @maxdate datetime=(select max(Asofdate) from vDailyCustomerCounts)
  declare @date datetime=@mindate
  declare @missing table(datevalue datetime )
  while @date<@maxdate
  begin
  if @date not in (select Asofdate from vDailyCustomerCounts)
  insert @missing 
  select @date
  set @date=@date+1 
  end 


select a.datevalue, 
    b.TotalCustomers ,
    b.HSDCustomers ,
    b.PhoneCustomers,
    b.VideoCustomers 
from (select Asofdate from vDailyCustomerCounts  
union select * from @missing )a 
        left join vDailyCustomerCounts b on a.Asofdate =b.Asofdate