Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8317791
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 8, 20262026-06-08T21:43:34+00:00 2026-06-08T21:43:34+00:00

SQL pivot question with a twist, Take the following table (note year and month

  • 0

SQL pivot question with a twist, Take the following table (note year and month are seperate):

CREATE TABLE [dbo].[tbl_BranchTargets]
    (
      [BranchID] [varchar](4) NOT NULL ,
      [Year] [smallint] NOT NULL ,
      [Month] [smallint] NOT NULL ,
      [Target] [int] NULL ,
      CONSTRAINT [PK_tbl_BranchTargets] PRIMARY KEY CLUSTERED ( [BranchID] ASC, [Year] ASC, [Month] ASC ) WITH ( PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON ) ON [PRIMARY]
    )
ON  [PRIMARY]

and the following dummy data:

INSERT [dbo].[tbl_BranchTargets] ([BranchID], [Year], [Month], [Target]) VALUES (N'001', 2012, 4, 1)
INSERT [dbo].[tbl_BranchTargets] ([BranchID], [Year], [Month], [Target]) VALUES (N'001', 2012, 5, 117)
INSERT [dbo].[tbl_BranchTargets] ([BranchID], [Year], [Month], [Target]) VALUES (N'001', 2012, 6, 233)
INSERT [dbo].[tbl_BranchTargets] ([BranchID], [Year], [Month], [Target]) VALUES (N'001', 2012, 7, 386)
INSERT [dbo].[tbl_BranchTargets] ([BranchID], [Year], [Month], [Target]) VALUES (N'003', 2012, 4, 2)
INSERT [dbo].[tbl_BranchTargets] ([BranchID], [Year], [Month], [Target]) VALUES (N'003', 2012, 6, 234)
INSERT [dbo].[tbl_BranchTargets] ([BranchID], [Year], [Month], [Target]) VALUES (N'003', 2012, 7, 387)

How would I model the given dummy data like this (note the year and month key columns are merged to form YYYYMM):

Raw Data

into this:

Expected Output

Note the missing entry for branch 3 in May, this needs to be handled as null. Eg, our of the 12 months, a branch might only have a target for 1 of them, so all the other months would need to be null.

I’ve looked into PIVOT() and clunky cursor options, but i am sturggling to find a quick best practice way of doing this, I’m assuming i need to implement some dynamic SQL + PIVOT() – but cant quite get my head round it.

I know that for dynamic pivots you first identify the column names (i think), i can do this as follows:

DECLARE @Columns AS NVARCHAR(MAX);
DECLARE @StrSQL AS NVARCHAR(MAX); 

SET @Columns = STUFF((SELECT DISTINCT
                            ',' + QUOTENAME(CONVERT(VARCHAR, c.YEAR) + RIGHT('00' + CONVERT(VARCHAR, c.MONTH), 2))
                   FROM     tbl_BranchTargets c
    FOR           XML PATH('') ,
                      TYPE 
            ).value('.', 'NVARCHAR(MAX)'), 1, 1, '') 

But how you perform the pivot is a bit beyond me (as i am essentially merging to key columns to create the final columns) – would i need to merge the data before attempting the pivot where YYYY + MM is defined as a value in 1 column?

(I am using SQL Server 2008 R2)

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-08T21:43:35+00:00Added an answer on June 8, 2026 at 9:43 pm

    You were very close to the final answer. You can use a PIVOT similar to the following (See SQL Fiddle with Demo):

    DECLARE @Columns AS NVARCHAR(MAX)
    DECLARE @StrSQL AS NVARCHAR(MAX) 
    
    SET @Columns = STUFF((SELECT DISTINCT
                                ',' + QUOTENAME(CONVERT(VARCHAR(4), c.YEAR) + RIGHT('00' + CONVERT(VARCHAR(2), c.MONTH), 2))
                       FROM     tbl_BranchTargets c
        FOR           XML PATH('') ,
                          TYPE 
                ).value('.', 'NVARCHAR(MAX)'), 1, 1, '') 
    
    set @StrSQL = 'SELECT branchid, ' + @Columns + ' from 
                (
                    select branchid
                        , target
                        , CONVERT(VARCHAR(4), [YEAR]) + RIGHT(''00'' + CONVERT(VARCHAR(2), [MONTH]), 2) dt
                    from tbl_BranchTargets
               ) x
                pivot 
                (
                    sum(target)
                    for dt in (' + @Columns + ')
                ) p '
    
    
    execute(@StrSQL)
    

    This will create the list of columns that you want at the execution time.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Using Django 1.1, how could I create a crosstab (pivot table) SQL query using
Possible Duplicate: SQL Server dynamic PIVOT query? I have temporary table with following structure:
Within my sql procedure I create an temporary table and then pivot it. This
I have to SQL Server views being drawn to 2 seperate worksheets as pivot
I have a Sql Database table similar to the following: Day Period Subject Mon
I have created a pivot table in MS Sql Server 2008. How can I
Possible Duplicate: T-SQL Pivot? Possibility of creating table columns from row values I've been
Possible Duplicate: dynamic sql pivot in sql server I have a table called Col_values
I have the following T-SQL Pivot query. SELECT AccountNumber, EventID, CreateDate, [ITEMBOOK] AS ITEMBOOK,
I'm new to SQL and the Pivot function. I want to pivot the following

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.