Getting daily counts for events that don't happen every day

后端 未结 3 1165
醉话见心
醉话见心 2021-01-20 21:29

I have a customer table in which a new row is inserted when a customer signup occurs.

Problem

I want to know the total numb

3条回答
  •  滥情空心
    2021-01-20 21:55

    DECLARE @MinDate DATE = '2015-07-01',
            @MaxDate DATE = '2015-07-10';
    
    Create Table tblTempDates 
    (created date, signup int)
    
    insert into tblTempDates
    SELECT  TOP (DATEDIFF(DAY, @MinDate, @MaxDate) + 1)
            Date = DATEADD(DAY, ROW_NUMBER() OVER(ORDER BY a.object_id) - 1, @MinDate),  0 As Signup
    FROM    sys.all_objects a
            CROSS JOIN sys.all_objects b;
    
    Create Table tblTempQueryDates
    (created date, signup int)
    
    INSERT INTO tblTempQueryDates
    SELECT 
        created AS created, COUNT(scandate) AS signup
    FROM
        customer
    WHERE
        created BETWEEN @MinDate AND @MaxDate
    GROUP BY created
    
    UPDATE    tblTempDates
    SET  tblTempDates.signup = tblTempQueryDates.signup            
    FROM         tblTempDates INNER JOIN
                          tblTempQueryDates ON tblTempDates.created = tblTempQueryDates.created
    
    select * from tblTempDates
    order by created
    
    Drop Table tblTempDates
    Drop Table tblTempQueryDates
    

    Not pretty, but it gives you what you want.

提交回复
热议问题