How to return a default value when no rows are returned from the select statement

前端 未结 7 1773
庸人自扰
庸人自扰 2021-01-22 13:26

I have a select statement that returns two columns, a date column, and a count(value) column. When the count(value) column doesn\'t have any records,

7条回答
  •  后悔当初
    2021-01-22 14:04

    To generate rows for missing dates you can join your data to a date dimension table

    It would look something like this:

    select convert(varchar(25), ddt.DateField, 101) as recordDate,
           count(t.Value) as recordCount
    from History h
    right join dbo.DateDimensionTable ddt
        on ddt.DateField = convert(varchar(25), h.DateTime, 101)
    where h.Value < 700
    group by convert(varchar(25), h.DateTime, 101)
    

    If your table uses the DateTime column to store dates only (meaning the time is always midnight), then you can replace this

    right join dbo.DateDimensionTable ddt
        on ddt.DateField = convert(varchar(25), h.DateTime, 101)
    

    with this

    right join dbo.DateDimensionTable ddt
        on ddt.DateField = h.DateTime
    

提交回复
热议问题