Adam Howitt's Blog

Apr 21
2006

SQL List of Numbers

Sometimes you want a sequence of numbers to join against, say a list of days in the month 1..31 and you want to have a row for each regardless of whether you have a matching row for that day, giving you a pivot table by day of the month.  Here is a SQL Server 2000 function to do this:

SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO

CREATE FUNCTION dbo.fn_getNumList (
/*
WRITTEN BY Adam Howitt adamhowitt@gmail.com
FUNCTION getDays
WRITTEN FOR SQL Server 2000
DATE 04.21.2006
Usage:
select currentNum
from fn_getNumList(0,60)
*/
@st_num int,
@num_to_add int )
RETURNS @numList TABLE ( currentNum int not null)
AS
BEGIN
    WHILE (@num_to_add > 0)
    BEGIN
        SET @st_num = 1+@st_num
        INSERT INTO @numList (currentNum)
        VALUES (@st_num)
        SET @num_to_add = @num_to_add - 1
    END
    RETURN
END

GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

So for example, you can use the following to retrieve a count of orders for each day of the month, including those where there were no orders.

select t1.currentNum, ISNULL(t2.numOrders,0) as numberOfOrders
from fn_getNumList(0,60) t1
LEFT JOIN (SELECT datepart(month,create_dt) as dom, count(*) as numOrders
FROM order_tb
GROUP BY datepart(month,create_dt)) t2
ON t1.currentNum = t2.dom

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
[Add Comment] [Subscribe to Comments]
  1. Thanks! This solves my problem as easy as 1, 2, 5

  2. I know that this is not a purely SQL example, but many times, when I want to do this, I declare a TABLE in SQL, then loop over it via CF and then join to a table. Pseudo code would be something like:

    DECLARE @t TABLE ( week_of INT );

    <cfloop...> INSERT INTO @t ( <cfqueryparam value="#dtWeekOf#" /> ) </cfloop>

    SELECT ... FROM mytable INNER JOIN @t1 ON ...

    So, its not a purely SQL statement, but its been a pretty easy and very useful thing for me. And, sorry, I don't remember the INSERT INTO syntax off hand at the moment.

  3. how simple! yet, you've just saved my life. : )

  4. Greatly appreciated, so simple yet I was struggling to think of a way to accomplish this with SQL

[Add Comment]