How to generate date in SQL Query?

 ̄綄美尐妖づ 提交于 2019-12-08 08:39:03

问题


I want to generate date value since 1/1/2011 - 31/12/2011 on sql query.

Example My Table A

Field A     Field B       Field C
   1       01/01/2011      125
   2       03/01/2011      100
   3       05/01/2011       50 

I want to result :

Field A     Field B       Field C
   1       01/01/2011      125
   0       02/01/2011        0
   2       03/01/2011      100
   0       04/01/2011        0
   3       05/01/2011       50 
   ...
   0       31/12/2011       0 

Please Advice Me and Thank a lot.


回答1:


Under SQL Server, you can create a table-valued function rather than creating a temporary table, as this is reusable between queries:

-- List all of the dates between startdate and enddate (inclusive)
CREATE FUNCTION [dbo].[DatesBetween] (
    @startdate date,
    @enddate date
) RETURNS @ret TABLE (Date date) AS BEGIN

    DECLARE @dt date, @dtEnd date
    SELECT @dt = @startdate, @dtEnd = @enddate

    WHILE (@dt <= @dtEnd) BEGIN
        INSERT INTO @ret VALUES(@dt)
        SET @dt = DATEADD(day, 1, @dt)
    END 

    RETURN
END

This allows everything to be executed inside one query:

SELECT d.Date, COUNT(t.*) AS TotalOnDay
FROM dbo.DatesBetween('2011-01-01', '2011-12-31') d 
    LEFT JOIN MyTable t ON t.Date = d.Date
GROUP BY d.Date



回答2:


If your "Field B" is formatted as Date, you can use the function DATEDIFF(Day,StartDate,EndDate) you can also change the "DATEDIFF(Day" to Year, Month or any other part you like.

hope this helps.




回答3:


In T-SQL you can write a query as:

CREATE TABLE #ALLDATE(Date1 date)
DECLARE @startDate DATE='1/1/2011'
DECLARE @endDate DATE='12/31/2011'

insert into #ALLDATE
SELECT [Date] = DATEADD(Day,Number,@startDate) 
FROM  master..spt_values 
WHERE Type='P'
AND DATEADD(day,Number,@startDate) <= @endDate

select * from #ALLDATE


来源:https://stackoverflow.com/questions/20687787/how-to-generate-date-in-sql-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!