Solved

How to have row data as columns SQL Query

Posted on 2011-02-23
3
349 Views
Last Modified: 2012-05-11
Hi,
I have a table with sample data:

GroupID, TaskID, LaborID, QTY
1, Fix Bulbs, 3, 5
1, Fix Stairs, 3, 2
1, Fix XYZ, 4, 1

I want to write a query that would display the LaborID as columns, and the TaskID as the rows.
I suppose this is Pivot, but I am not clear. Been a long month.
0
Comment
Question by:melegant99
  • 2
3 Comments
 
LVL 26

Expert Comment

by:tigin44
ID: 34964332
simple try this
SELECT TaskID, [1],[2],[3],[4],[5],[6]
FROM (

		SELECT TaskID, LaborID 
		FROM yourTable	
	) P
	PIVOT
	(
		MAX(LaborID) FOR LaborID IN ([1],[2],[3],[4],[5],[6])
	) AS pvt
ORDER BY TaskID

Open in new window

0
 

Author Comment

by:melegant99
ID: 34964539
I don't know what the LaborID's will be though in advance, it could be any varying amount and ID #.
0
 
LVL 26

Accepted Solution

by:
tigin44 earned 500 total points
ID: 34964565
then you should create the pivot sql dynamically...

just create this part [1],[2],[3],[4],[5],[6] from the table by using a query that will include all the values.. and concat it twith the given query and execute it...

0

Featured Post

Optimizing Cloud Backup for Low Bandwidth

With cloud storage prices going down a growing number of SMBs start to use it for backup storage. Unfortunately, business data volume rarely fits the average Internet speed. This article provides an overview of main Internet speed challenges and reveals backup best practices.

Question has a verified solution.

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

Suggested Solutions

Never store passwords in plain text or just their hash: it seems a no-brainier, but there are still plenty of people doing that. I present the why and how on this subject, offering my own real life solution that you can implement right away, bringin…
In this article we will learn how to fix  “Cannot install SQL Server 2014 Service Pack 2: Unable to install windows installer msi file” error ?
Using examples as well as descriptions, and references to Books Online, show the documentation available for date manipulation functions and by using a select few of these functions, show how date based data can be manipulated with these functions.
Via a live example, show how to setup several different housekeeping processes for a SQL Server.

740 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