SQL SERVER uses spt_values to generate continuous date data

        Sometimes when we display data, we want to display the data of all days of the month, but only the dates with data are stored in our database, and the data that has no data inserted on that day will not be stored, for example:

--Test Data
if not object_id(N'Tempdb..#T') is null
	drop table #T
Go
Create table #T([DataTime] Date,[DataValue] int)
Insert #T
select '2018-03-02',100 union all
select '2018-03-05',300 union all
select '2018-03-10',230 union all
select '2018-03-20',670
Go
-- end of test data
Select * from #T

        We want to display the DataValue values ​​of all dates in March. If there is no value, it will be displayed as 0, but only 4 pieces of data are stored in our database. At this time, we can use a long SQL table spt_values ​​to achieve, the method is as follows:

SELECT DATEADD(DAY, number, CONVERT(DATETIME, '2018-03-01')) [DataTime],
       ISNULL(DataValue,0) DataValue
FROM master..spt_values
    LEFT JOIN #T
        ON DATEADD(DAY, number, CONVERT(DATETIME, '2018-03-01')) = [DataTime]
WHERE type = 'P'
      AND number
      BETWEEN 0 AND DATEDIFF(DAY, '2018-03-01', DATEADD(MONTH, 1, '2018-03-01'))-1;

        The result is as follows:


        In the above, we have realized the need to display all the dates of the current month through spt_values. Of course, we can also flexibly change, read every year, or multiple months, etc., all can be flexibly realized.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325808536&siteId=291194637