SQL Count for each date

后端 未结 7 673
盖世英雄少女心
盖世英雄少女心 2021-02-03 21:57

I have the following need

I have a logging table which logs som leads generated each day.

Now I need to pull a report over the amount of leads for each day over

相关标签:
7条回答
  • 2021-02-03 22:25

    It is most efficient to do your aggregation by integer and then convert back to datetime for presentation.

    select 
        cast(daybucket - 1 as datetime) as count_date,
        counted_leads
    from 
        (select 
             cast(created_date as int) as DayBucket,
             count(*) as counted_leads
         from mytable
         group by cast(created_date as int) ) as countByDay
    
    0 讨论(0)
  • 2021-02-03 22:27

    When you cast a DateTime to an int it "truncates" at noon, you might want to strip the day out like so

    cast(DATEADD(DAY, DATEDIFF(DAY, 0, created_date), 0) as int) as DayBucket
    
    0 讨论(0)
  • 2021-02-03 22:30
    CREATE PROCEDURE [dbo].[sp_Myforeach_Date]
        -- Add the parameters for the stored procedure here
        @SatrtDate as DateTime,
        @EndDate as dateTime,
        @DatePart as varchar(2),
        @OutPutFormat as int 
    AS
    BEGIN
        -- SET NOCOUNT ON added to prevent extra result sets from
        -- interfering with SELECT statements.
        Declare @DateList Table
        (Date varchar(50))
    
        WHILE @SatrtDate<= @EndDate
        BEGIN
        INSERT @DateList (Date) values(Convert(varchar,@SatrtDate,@OutPutFormat))
        IF Upper(@DatePart)='DD'
        SET @SatrtDate= DateAdd(dd,1,@SatrtDate)
        IF Upper(@DatePart)='MM'
        SET @SatrtDate= DateAdd(mm,1,@SatrtDate)
        IF Upper(@DatePart)='YY'
        SET @SatrtDate= DateAdd(yy,1,@SatrtDate)
        END 
        SELECT * FROM @DateList
    END
    

    Just put this Code and call the SP in This way

    exec sp_Myforeach_Date @SatrtDate='03 Jan 2010',@EndDate='03 Mar 2010',@DatePart='dd',@OutPutFormat=106
    

    Thanks Suvabrata Roy ICRA Online Ltd. Kolkata

    0 讨论(0)
  • 2021-02-03 22:36

    You can use:

    Select
         count(created_date) as counted_leads,
         created_date as count_date
    from
         table
    group by
         created_date
    
    0 讨论(0)
  • 2021-02-03 22:45

    I had similar question however mine involved a column Convert(date,mydatetime). I had to alter the best answer as follows:

    Select
         count(created_date) as counted_leads,
         Convert(date,created_date) as count_date 
    from table
    group by Convert(date,created_date)
    
    0 讨论(0)
  • 2021-02-03 22:47

    Your created_date field is datetime, so you'll need to strip off the time before the grouping will work if you want to go by date:

    SELECT COUNT(created_date), created_date 
    FROM table 
    WHERE DATEDIFF(created_date, getdate()) < 10
    GROUP BY convert(varchar, created_date, 101)
    
    0 讨论(0)
提交回复
热议问题