Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
Stanley Tan
Starting Member
25 Posts |
Posted - 2003-06-27 : 07:03:36
|
| Hi,Is it possible to create a SQL statement that will return all date values from a given start and end point? For instance:Start: 05/01/03End: 05/05/03Result:05/01/03 some data05/02/03 some other data05/03/0305/04/03 some data05/05/03 blah blahThis query:SELECT MyDate, SUM(Amount) FROM MyTableGROUP BY MyDatedoes not generate the desired output if some dates are not present in the table such as 05/03/03 (should display blank data field).Any help is greatly appreciated. :) |
|
|
dsdeming
479 Posts |
Posted - 2003-06-27 : 08:50:10
|
| Yes. You can use a number table ( sometimes called a sequence or tally table ). There are several threads on the subjects in the forums. I use a table called Sequence with a single integer column called Counter that holds values from 1 - 8000. Basically it works like this:DECLARE @dtFirst datetime, @TotalDays int-- the CONVERTS on the datetime column are only required if you-- need to strip the timeSELECT @dtFirst = MIN( CONVERT( datetime, CONVERT( char( 8 ), YourDateColumn, 112 ) )), @TotalDays = DATEDIFF( dd, MIN( CONVERT( datetime, CONVERT( char( 8 ), YourDateColumn, 112 ) )), MAX( CONVERT( datetime, CONVERT( char( 8 ), YourDateColumn, 112 ) )))FROM YourTableSELECT AllDays = DATEADD( dd, Counter - 1, @dtFirst ) FROM SequenceWHERE Counter <= @TotalDays + 1The last SELECT statement could easily be joined in a more complex select.Dennis |
 |
|
|
|
|
|
|
|