Solved

ms sql -- display multiple columns, one row

Posted on 2013-05-29
9
835 Views
Last Modified: 2013-06-02
How can I change one of the below to
"display multiple columns, one rows"
so it looks the the attached
 
I just want to use a SQL statement, no storedProc/etc.
------------------------------------------------------------------------------
  Test #1 --> displays one column, multiple rows
     SELECT status + '_' + work_center as WC_Status
     FROM job_operation
     where job = '1573' --> I will change this to a parameter later
------------------------------------------------------------------------------
  Test #2 --> displays one column, one row
     SELECT work_center + ','
     FROM job_operation
     where
       job = 'G0878' --> I will change this to a parameter later
     FOR XML PATH('')
s003.jpg
0
Comment
Question by:finance_teacher
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
  • 2
9 Comments
 
LVL 41

Expert Comment

by:Sharath
ID: 39205338
Do you just want to transpose rows data to columns? Can you post some sample from your query?

SELECT status + '_' + work_center as WC_Status
     FROM job_operation
     where job = '1573'
0
 

Author Comment

by:finance_teacher
ID: 39205357
Attached is sample data for the below.

I want the end result to look like the attached, displaying multiple columns, but JUST one row per job #

I am only passing one job # parameter at a time.

CREATE TABLE [dbo].[Job_Operation_test](
      [Job] [dbo].[Key10] NULL,
      [Work_Center] [dbo].[Key10] NULL
s004.jpg
data.txt
0
 

Author Comment

by:finance_teacher
ID: 39205378
attached is the FULL script if needed
script.sql
0
PeopleSoft Has Never Been Easier

PeopleSoft Adoption Made Smooth & Simple!

On-The-Job Training Is made Intuitive & Easy With WalkMe's On-Screen Guidance Tool.  Claim Your Free WalkMe Account Now

 
LVL 41

Expert Comment

by:Sharath
ID: 39205465
Can you try this?
IF OBJECT_ID('tempdb..#Results') IS NOT NULL
    DROP TABLE #Results
	
SELECT DISTINCT Job, Work_Center,
       ROW_NUMBER() OVER (PARTITION BY Job ORDER BY Work_Center) rn
  INTO #Results
  FROM Job_Operation_test;

DECLARE @listStr VARCHAR(MAX)
 SELECT @listStr = COALESCE(@listStr+',' ,'') + '[' + convert(varchar,rn) + ']' 
   FROM (select distinct rn from #Results) t1
 

SELECT @listStr = 
'SELECT *
  FROM #Results
 PIVOT (MAX(Work_Center) FOR rn IN ('+@listStr+')) P'

EXEC (@listStr)

Open in new window


Tested with some sample data: http://sqlfiddle.com/#!3/3025c/17
0
 
LVL 41

Expert Comment

by:Sharath
ID: 39205482
Fixed duplicate data issue
IF OBJECT_ID('tempdb..#Results') IS NOT NULL
    DROP TABLE #Results
	
SELECT *, 
       ROW_NUMBER() OVER (PARTITION BY Job ORDER BY Work_Center) rn
  INTO #Results
  FROM (SELECT DISTINCT Job, Work_Center FROM Job_Operation_test 
         WHERE Work_Center IS NOT NULL) t1;

DECLARE @listStr VARCHAR(MAX)
 SELECT @listStr = COALESCE(@listStr+',' ,'') + '[' + convert(varchar,rn) + ']' 
   FROM (select distinct rn from #Results) t1
 

SELECT @listStr = 
'SELECT *
  FROM #Results
 PIVOT (MAX(Work_Center) FOR rn IN ('+@listStr+')) P'

EXEC (@listStr)

Open in new window


Tested with some sample data: http://sqlfiddle.com/#!3/3025c/19
0
 

Author Comment

by:finance_teacher
ID: 39205578
Below Test #1, Test #2, Test #3, and Test #4 work.

I then run Test #4 and Test #5 at the same time in MS SQL 2005 Server Management Studio and get an Incorrect syntax near '('. error.

How can I get the statements to work inside MS SQL Reporting Services or reduce it to SQL that works with MS SQL 2005 Server Management Studio ?
-----------------------------------------------------------------------------------------------------
--Test #1
DROP TABLE #Results

--Test #2
SELECT *,
       ROW_NUMBER() OVER (PARTITION BY Job ORDER BY Work_Center) rn
  INTO #Results
  FROM (SELECT DISTINCT Job, Work_Center FROM Job_Operation_test
         WHERE Work_Center IS NOT NULL) t1;

--Test #3
select * from #Results

--Test #4
DECLARE @listStr VARCHAR(MAX)
 SELECT @listStr = COALESCE(@listStr+',' ,'') + '[' + convert(varchar,rn) + ']'
   FROM (select distinct rn from #Results) t1;
SELECT @listStr =
'SELECT *
  FROM #Results
 PIVOT (MAX(Work_Center) FOR rn IN ('+@listStr+')) P'; -- Incorrect syntax near '('.

--Test #5
EXEC (@listStr);
0
 
LVL 41

Assisted Solution

by:Sharath
Sharath earned 250 total points
ID: 39205825
I did not see any issue. Can you run these and post the SQL printed.

--Test #4
DECLARE @listStr VARCHAR(MAX)
 SELECT @listStr = COALESCE(@listStr+',' ,'') + '[' + convert(varchar,rn) + ']'
   FROM (select distinct rn from #Results) t1;
SELECT @listStr =
'SELECT *
  FROM #Results
 PIVOT (MAX(Work_Center) FOR rn IN ('+@listStr+')) P'; -- Incorrect syntax near '('.

--Test #5
SELECT (@listStr);
0
 
LVL 48

Expert Comment

by:PortletPaul
ID: 39206997
I have a question about the expected results which your images don't reveal. In the following there are 15 rows of data for job 1573. Under that are 4 output options
a. the full 15, in the sequence found (with nulls)
b. as for a but nulls removed
c. unique work centers, based on sequence found
d. unique work centers, in alpha order
which of these is the required output?
INSERT [dbo].[Job_Operation_test] ([Job], [Work_Center]) VALUES (N'1573', N'ENGINEER')
INSERT [dbo].[Job_Operation_test] ([Job], [Work_Center]) VALUES (N'1573', N'INSPECTION')
INSERT [dbo].[Job_Operation_test] ([Job], [Work_Center]) VALUES (N'1573', N'INSPECTION')
INSERT [dbo].[Job_Operation_test] ([Job], [Work_Center]) VALUES (N'1573', N'WATERJET L')
INSERT [dbo].[Job_Operation_test] ([Job], [Work_Center]) VALUES (N'1573', N'HAASMINI 1')
INSERT [dbo].[Job_Operation_test] ([Job], [Work_Center]) VALUES (N'1573', N'DEBURR')
INSERT [dbo].[Job_Operation_test] ([Job], [Work_Center]) VALUES (N'1573', N'INSPECTION')
INSERT [dbo].[Job_Operation_test] ([Job], [Work_Center]) VALUES (N'1573', NULL)
INSERT [dbo].[Job_Operation_test] ([Job], [Work_Center]) VALUES (N'1573', NULL)
INSERT [dbo].[Job_Operation_test] ([Job], [Work_Center]) VALUES (N'1573', N'GEN LABOR')
INSERT [dbo].[Job_Operation_test] ([Job], [Work_Center]) VALUES (N'1573', N'PAINT')
INSERT [dbo].[Job_Operation_test] ([Job], [Work_Center]) VALUES (N'1573', N'INSPECTION')
INSERT [dbo].[Job_Operation_test] ([Job], [Work_Center]) VALUES (N'1573', N'GEN LABOR')
INSERT [dbo].[Job_Operation_test] ([Job], [Work_Center]) VALUES (N'1573', N'SOURCE')
INSERT [dbo].[Job_Operation_test] ([Job], [Work_Center]) VALUES (N'1573', N'GEN LABOR')

a
ENGINEER,INSPECTION,INSPECTION,WATERJET L,HAASMINI 1,DEBURR,INSPECTION,NULL,NULL,GEN LABOR,PAINT,INSPECTION,GEN LABOR,SOURCE,GEN LABOR
b
ENGINEER,INSPECTION,INSPECTION,WATERJET L,HAASMINI 1,DEBURR,INSPECTION,GEN LABOR,PAINT,INSPECTION,GEN LABOR,SOURCE,GEN LABOR
c
ENGINEER,INSPECTION,WATERJET L,HAASMINI 1,DEBURR,GEN LABOR,PAINT,SOURCE
d
DEBURR,ENGINEER,GEN LABOR,HAASMINI 1,INSPECTION,PAINT,SOURCE,WATERJET L

Open in new window

0
 
LVL 48

Accepted Solution

by:
PortletPaul earned 250 total points
ID: 39207114
your image shows repitition of work_center across the row, so that's why I wonder if you want options A or B in particular. I think Sharath's prior code provides option D by the way.

code for options A, B  :: http://sqlfiddle.com/#!3/3de4d/6

-- Option A
IF OBJECT_ID('tempdb..#Results') IS NOT NULL
    DROP TABLE #Results;

DECLARE @query  AS NVARCHAR(MAX)

SELECT Job, Work_Center,
       ROW_NUMBER() OVER (PARTITION BY Job ORDER BY getdate()) row_ref
INTO #Results
FROM Job_Operation_test

;WITH
COLS AS (
          SELECT
              ', max(CASE WHEN row_ref = '
            + convert(varchar,number)
            + ' THEN Work_Center ELSE null END) AS ['
            + convert(varchar,number) + ']'
            AS casea
          FROM master.dbo.spt_values
          WHERE  TYPE = 'P'
          AND number BETWEEN 1 AND (
                                    SELECT max(row_ref)
                                    FROM #Results
                                    )
           )


select @query = 

  'select Job, ' 
+ STUFF( 
           ( SELECT casea
             FROM cols
             FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')  
+ ' from #Results group by Job'

exec(@query)
;

-- Option B
IF OBJECT_ID('tempdb..#Results') IS NOT NULL
    DROP TABLE #Results;

DECLARE @query  AS NVARCHAR(MAX)

SELECT Job, Work_Center,
       ROW_NUMBER() OVER (PARTITION BY Job ORDER BY getdate()) row_ref
INTO #Results
FROM Job_Operation_test
WHERE work_center is not null


;WITH
COLS AS (
          SELECT
              ', max(CASE WHEN row_ref = '
            + convert(varchar,number)
            + ' THEN Work_Center ELSE null END) AS ['
            + convert(varchar,number) + ']'
            AS casea
          FROM master.dbo.spt_values
          WHERE  TYPE = 'P'
          AND number BETWEEN 1 AND (
                                    SELECT max(row_ref)
                                    FROM #Results
                                    )
           )


select @query = 

  'select Job, ' 
+ STUFF( 
           ( SELECT casea
             FROM cols
             FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')  
+ ' from #Results group by Job'

exec(@query)
;
-- option C not available
;

-- option D
IF OBJECT_ID('tempdb..#Results') IS NOT NULL
    DROP TABLE #Results;

DECLARE @query  AS NVARCHAR(MAX)

SELECT  DISTINCT Job, Work_Center, 1 row_ref
INTO #Results
FROM Job_Operation_test
WHERE work_center is not null

UPDATE #Results
set row_ref = (
                select row_ref
                from (
                      select job, work_center
                  , ROW_NUMBER() OVER (PARTITION BY Job ORDER BY work_center) row_ref
                      from #Results
                     ) r
                where #Results.Job = r.Job and #Results.Work_Center = r.Work_Center
              )

;WITH
COLS AS (
          SELECT
              ', max(CASE WHEN row_ref = '
            + convert(varchar,number)
            + ' THEN Work_Center ELSE null END) AS ['
            + convert(varchar,number) + ']'
            AS casea
          FROM master.dbo.spt_values
          WHERE  TYPE = 'P'
          AND number BETWEEN 1 AND (
                                    SELECT max(row_ref)
                                    FROM #Results
                                    )
           )


select @query = 

  'select Job, ' 
+ STUFF( 
           ( SELECT casea
             FROM cols
             FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')  
+ ' from #Results group by Job'

--select @query -- uncomment to inspect what the variable contains
exec(@query)
;

Open in new window

a different option D is here also but it probably offers nothing that using the pivot command won't
0

Featured Post

Efficient way to get backups off site to Azure

This user guide provides instructions on how to deploy and configure both a StoneFly Scale Out NAS Enterprise Cloud Drive virtual machine and Veeam Cloud Connect in the Microsoft Azure Cloud.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

This article describes how to use the timestamp of existing data in a database to allow Tableau to calculate the prior work day instead of relying on case statements or if statements to calculate the days of the week.
Ever needed a SQL 2008 Database replicated/mirrored/log shipped on another server but you can't take the downtime inflicted by initial snapshot or disconnect while T-logs are restored or mirror applied? You can use SQL Server Initialize from Backup…
I've attached the XLSM Excel spreadsheet I used in the video and also text files containing the macros used below. https://filedb.experts-exchange.com/incoming/2017/03_w12/1151775/Permutations.txt https://filedb.experts-exchange.com/incoming/201…
Attackers love to prey on accounts that have privileges. Reducing privileged accounts and protecting privileged accounts therefore is paramount. Users, groups, and service accounts need to be protected to help protect the entire Active Directory …

751 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question