sql - Query to arrange rows horizontally -
i have 2 tables need join , produce third table columns arranged horizontally. tables follows:
i need output 2 table1
, table2
.
i did research , found need use pivot
. wrote query also. query
select * ( select convert(char(4), table_2.date, 100) + convert(char(4), table_2.date, 120) registrationdate, table_1.pdesc productdescription table_2 left outer join table_1 on table_1.pid = table_2.pid ) tablet pivot (count(productdescription) registrationdate in ([jan 2009],[feb 2009],[mar 2009],[apr 2009],[may 2009],[jun 2009])) pvt
but query not working! have attached sql script create tables.
i have uploaded script here .
the problem attempting both count
, display productdescription
. if want display productdescription
there few different ways can this.
instead of applying count
productdescription
, can count
pid
column:
select * ( select convert(char(4), t2.date, 100) + convert(char(4), t2.date, 120) registrationdate, t1.productdesc productdescription, t1.pid table_2 t2 left outer join table_1 t1 on t1.pid = t2.pid ) tablet pivot ( count(pid) registrationdate in ([jan 2009],[feb 2009],[mar 2009],[apr 2009],[may 2009],[jun 2009]) ) pvt;
see sql fiddle demo.
or can create second column in subquery return productdescription
twice. 1 column used in count , second used in final display:
select * ( select convert(char(4), t2.date, 100) + convert(char(4), t2.date, 120) registrationdate, t1.productdesc productdescription, t1.productdesc product table_2 t2 left outer join table_1 t1 on t1.pid = t2.pid ) tablet pivot ( count(productdescription) registrationdate in ([jan 2009],[feb 2009],[mar 2009],[apr 2009],[may 2009],[jun 2009]) ) pvt;
see sql fiddle demo
Comments
Post a Comment