Click here to Skip to main content
15,886,110 members
Please Sign up or sign in to vote.
2.50/5 (2 votes)
See more:
In table records as follows
Facid  Q1 Q2 Q3   Batchid
 1     2  3  4     B001
 2     4  4  5     B001
 1     5  1  2     B002
 2     4  5  3     B002
 1     4  1  2     B003
 2     5  4  3     B003


Using above records i want output as follows using sql query
             B001             B002             B003
Facid     Q1  Q2  Q3       Q1  Q2   Q3         Q1  Q2   Q3

 1        2   3   4         5   1   2           4   1    2
 2        4   4   5         4   5   3           5   4    3


for getting a above output how can i write a sql query.

please help me.

Regards
Narasiman
Posted
Updated 16-Jun-14 7:27am
v2
Comments
Herman<T>.Instance 16-Jun-14 13:54pm    
you are looking for pivotting with double header or consider headernames like B001_Q1, B001_Q2
[no name] 16-Jun-14 22:22pm    
pivotting with double header
TheSqlGuy 20-Jun-14 22:50pm    
What type of database is this,e.g., Oracle, SQL, DB2, etc.?
coded007 20-Aug-14 5:21am    
pivoting with double header is not possible in SQL

Was focusing on getting the data there as the extra header is a presentation aspect and not really interesting, so while you could do a pivot i think the cross apply is more agile in this circumstance. Especially because of it's inherent ability to simply add cross applies based on data if a dynamic query version is chosen.

SQL
declare @grp table(
    facid int
    )
insert into @grp(facid)
(select distinct facid from @tbl)

select facid, c.*, d.*, e.*
from @grp a
cross apply(
    select q1, q2, q3 from @tbl b where b.batchid = 'B001' and a.facid = b.facid
) c
cross apply(
    select q1, q2, q3 from @tbl b where b.batchid = 'B002' and a.facid = b.facid
) d
cross apply(
    select q1, q2, q3 from @tbl b where b.batchid = 'B003' and a.facid = b.facid
) e
/* you could generate query dynamically to make the batches based on actual data
and avoid hardcoding for instance from csharp  */
 
Share this answer
 
Hi,

Check this...

Simple Way To Use Pivot In SQL Query[^]

Hope this will help you.

Cheers
 
Share this answer
 
Pivoting double header is not possible in SQL.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900