creating a table to show month and year

  • I need to refer to a temp table which has all the months and dynamically shows the years.

    for example I need rolling 12 months to show in this table:

    November 2012

    December 2012

    January 2013

    February 2013

    March 2013

    April 2013

    May 2013

    June 2013

    July 2013

    August 2013

    September 2013

    October 2013

    And when we are in december I would expect december 2012 to be at the top and an extra line for November 2013. (November 2012 to dissapear).

    Is this possible?

  • CREATE TABLE #yourTempTable([MonthName] VARCHAR(9), [Year] INT);

    WITH CTE(N) AS (SELECT 1 FROM (SELECT 1 UNION ALL SELECT 1)a(N)),

    CTE2(N) AS (SELECT 1 FROM CTE x CROSS JOIN CTE y),

    CTE3(N) AS (SELECT 1 FROM CTE2 x CROSS JOIN CTE2 y),

    TALLY(N) AS (SELECT 0 UNION ALL

    SELECT TOP 11 ROW_NUMBER() OVER(ORDER BY (SELECT NULL))

    FROM CTE3),

    DATETALLY(N) AS (SELECT DATEADD(month, DATEDIFF(month, 0, GETDATE())+N, 0)

    FROM TALLY)

    INSERT INTO #yourTempTable

    SELECT DATENAME(month,N), YEAR(N)

    FROM DATETALLY;

    SELECT *

    FROM #yourTempTable;


    Forever trying to learn
    My blog - http://www.cadavre.co.uk/
    For better, quicker answers on T-SQL questions, click on the following...http://www.sqlservercentral.com/articles/Best+Practices/61537/
    For better, quicker answers on SQL Server performance related questions, click on the following...http://www.sqlservercentral.com/articles/SQLServerCentral/66909/

  • Fantastic thank you

  • Sachin 80451 (12/3/2012)


    Fantastic thank you

    No problem. Do you understand how it works?


    Forever trying to learn
    My blog - http://www.cadavre.co.uk/
    For better, quicker answers on T-SQL questions, click on the following...http://www.sqlservercentral.com/articles/Best+Practices/61537/
    For better, quicker answers on SQL Server performance related questions, click on the following...http://www.sqlservercentral.com/articles/SQLServerCentral/66909/

  • Unfortunately i dont have the faintest idea.

    Is there any way you can break it down for me?

  • Sachin 80451 (12/6/2012)


    Unfortunately i dont have the faintest idea.

    Is there any way you can break it down for me?

    Okay let me thave a go.

    Cadavre introduces the concept of a tally table. In his solution he creates the table on the fly which is great but as this numbers table is so useful I highly recommend you create this table permanently in a utility database perhaps?

    Here is one way of creating the Tally table:

    If exists (select 1 from information_schema.tables where table_name = 'Tally')

    drop table dbo.[Tally]

    GO

    CREATE TABLE dbo.Tally (N INT,CONSTRAINT PK_Tally_N PRIMARY KEY CLUSTERED (N))

    DECLARE @Counter INT

    SET @Counter = 0

    WHILE @Counter <= 10000

    BEGIN

    INSERT INTO dbo.Tally (N)

    VALUES (@Counter)

    SET @Counter = @Counter + 1

    Now that we have our numbers we can get the first day of each month as follows:

    SELECT DATEADD(month, DATEDIFF(month, 0, GETDATE())+N, 0) as N

    FROM TALLY

    The above bit of code looks complicated but I will try and explain. Our goal is to get one record per month as per yor requirement. To do this we start with:

    SELECT DATEDIFF(month, 0, GETDATE())+N

    FROM TALLY

    This gives us the number of months since 01/01/1900 this is the date you get when you cast the value 0 as a date. So the above query will run somethign like this.

    1) Number of months since 01/01/1900 to this day = 1355 + N (tally table starts at 0) so = 1355

    2) Number of months since 01/01/1900 to this day = 1355 + N (next value of N is 1 ) so = 1356

    and so on.

    If we then add the number of months back to 01/01/1900 we will get back 1 record per month

    And to get the name we can make the above a derived table or CTE as follows:

    select DATENAME(month,N), YEAR(N)

    FROM (SELECT DATEADD(month, DATEDIFF(month, 0, GETDATE())+N, 0) as N

    FROM TALLY) as a

    Hope this helps.

    ---------------------------------------------------------

    It takes a minimal capacity for rational thought to see that the corporate 'free press' is a structurally irrational and biased, and extremely violent, system of elite propaganda.
    David Edwards - Media lens[/url]

    Society has varying and conflicting interests; what is called objectivity is the disguise of one of these interests - that of neutrality. But neutrality is a fiction in an unneutral world. There are victims, there are executioners, and there are bystanders... and the 'objectivity' of the bystander calls for inaction while other heads fall.
    Howard Zinn

  • Cadavre (12/3/2012)


    CREATE TABLE #yourTempTable([MonthName] VARCHAR(9), [Year] INT);

    WITH CTE(N) AS (SELECT 1 FROM (SELECT 1 UNION ALL SELECT 1)a(N)),

    CTE2(N) AS (SELECT 1 FROM CTE x CROSS JOIN CTE y),

    CTE3(N) AS (SELECT 1 FROM CTE2 x CROSS JOIN CTE2 y),

    TALLY(N) AS (SELECT 0 UNION ALL

    SELECT TOP 11 ROW_NUMBER() OVER(ORDER BY (SELECT NULL))

    FROM CTE3),

    DATETALLY(N) AS (SELECT DATEADD(month, DATEDIFF(month, 0, GETDATE())+N, 0)

    FROM TALLY)

    INSERT INTO #yourTempTable

    SELECT DATENAME(month,N), YEAR(N)

    FROM DATETALLY;

    SELECT *

    FROM #yourTempTable;

    Jeff Moden would probably be disappointed with me if I didn't post this somewhat terser version:

    SELECT Month=DATENAME(month, MyDate), Year=DATEPART(year, MyDate)

    FROM [master].dbo.spt_values Tally

    CROSS APPLY (

    SELECT DATEADD(month, number-1, GETDATE())) a (MyDate)

    WHERE [Type] = 'P' AND Number BETWEEN 1 AND 12


    My mantra: No loops! No CURSORs! No RBAR! Hoo-uh![/I]

    My thought question: Have you ever been told that your query runs too fast?

    My advice:
    INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
    The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.

    Need to UNPIVOT? Why not CROSS APPLY VALUES instead?[/url]
    Since random numbers are too important to be left to chance, let's generate some![/url]
    Learn to understand recursive CTEs by example.[/url]
    [url url=http://www.sqlservercentral.com/articles/St

  • Sachin 80451 (12/3/2012)


    I need to refer to a temp table which has all the months and dynamically shows the years.

    for example I need rolling 12 months to show in this table:

    Since there are no DATETIME reference columns in that table, I have to ask... WHY? What and how are you going to use this? I'm not trying to be difficult here. I just see a world of hurt coming up and I'm trying to help you avoid it. In order to do that, I need to know what and how you intend to use this table.

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)

Viewing 8 posts - 1 through 7 (of 7 total)

You must be logged in to reply to this topic. Login to reply