Solved

ms sql -- display multiple columns, one row

Posted on 2013-05-29
9
811 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
  • 4
  • 3
  • 2
9 Comments
 
LVL 40

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
Best Practices: Disaster Recovery Testing

Besides backup, any IT division should have a disaster recovery plan. You will find a few tips below relating to the development of such a plan and to what issues one should pay special attention in the course of backup planning.

 
LVL 40

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 40

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 40

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

Gigs: Get Your Project Delivered by an Expert

Select from freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely and get projects done right.

Question has a verified solution.

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

'Between' is such a common word we rarely think about it but in SQL it has a very specific definition we should be aware of. While most database vendors will have their own unique phrases to describe it (see references at end) the concept in common …
If you have heard of RFC822 date formats, they can be quite a challenge in SQL Server. RFC822 is an Internet standard format for email message headers, including all dates within those headers. The RFC822 protocols are available in detail at:   ht…
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, just open a new email message. In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
Established in 1997, Technology Architects has become one of the most reputable technology solutions companies in the country. TA have been providing businesses with cost effective state-of-the-art solutions and unparalleled service that is designed…

813 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now