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

前端 未结 7 1774
庸人自扰
庸人自扰 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 13:56

    The best practice would be for you to have a datamart where a separate dimensional table for dates is kept with all dates you might be interested at - even if they lack amounts. DMason's answer shows the query with such a dimensional table.

    To keep with the best practices you would have a fact table where you'd keep these historical data already pre-grouped at the granularity level you need (daily, in this case), so you wouldn't need a GROUP BY unless you needed a coarser granularity (weekly, monthly, yearly).

    And in both your operational and datamart databases the dates would be stored as dates, not...

    But then, since this is real world and you might not be able to change what somebody else made... If you: a) only care about the dates that appear in [History], and b) such dates are never stored with hours/minutes; then following query might be what you'd need:

    SELECT MyDates.DateTime, COUNT(*)-1 AS RecordCount
    FROM (
          SELECT DISTINCT DateTime FROM History
       ) MyDates
    LEFT JOIN History H
      ON  MyDates.DateTime = H.Datetime
      AND H.Value < 700
    GROUP BY MyDates.DateTime
    

    Do try to add an index over DateTime and to further constrain the query with an earliest/latest date for better performance results.

提交回复
热议问题