Domanda

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.

È stato utile?

Soluzione

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

Altri suggerimenti

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.

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
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top