Solved

How to have row data as columns SQL Query

Posted on 2011-02-23
3
339 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

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

CCModeler offers a way to enter basic information like entities, attributes and relationships and export them as yEd or erviz diagram. It also can import existing Access or SQL Server tables with relationships.
Ever wondered why sometimes your SQL Server is slow or unresponsive with connections spiking up but by the time you go in, all is well? The following article will show you how to install and configure a SQL job that will send you email alerts includ…
Via a live example, show how to extract information from SQL Server on Database, Connection and Server properties
Via a live example, show how to extract insert data into a SQL Server database table using the Import/Export option and Bulk Insert.

705 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

18 Experts available now in Live!

Get 1:1 Help Now