sql - How to transpose recordset columns into rows -
i have query code looks this:
select documentid, complexsubquery1 ... complexsubquery5 document ...
complexsubquery numerical fields calculated using, duh, complex subqueries.
i use query subquery query generates summary following one:
field documentcount total 1 dc1 s1 2 dc2 s2 3 dc3 s3 4 dc4 s4 5 dc5 s5
where:
dc<n> = sum(case when complexsubquery<n> > 0 1 end) s <n> = sum(case when field = n complexsubquery<n> end)
how in sql server?
note: know avoid problem discarding original query , using unions:
select '1' typeid, sum(case when complexsubquery1 > 0 1 end) documentcount sum(complexsubquery1) total (select documentid, blargh ... complexsubquery1) t union select '2' typeid, sum(case when complexsubquery2 > 0 1 end) documentcount sum(complexsubquery2) total (select documentid, blargh ... complexsubquery2) t union ...
but want avoid route, because redundant code makes eyes bleed. (besides, there real possibility number of complex subqueries grow in future.)
with document(documentid, field) ( select 1, 1 union select 2, 1 union select 3, 2 union select 4, 3 union select 5, 4 union select 6, 5 union select 7, 5 ), cte ( select documentid, field, (select 10) complexsubquery1, (select 20) complexsubquery2, (select 30) complexsubquery3, (select 40) complexsubquery4, (select 50) complexsubquery5 document ) select field, sum(case when right(query,1) = field , queryvalue > 1 1 end ) documentcount, sum(case when right(query,1) = field queryvalue end ) total cte unpivot (queryvalue query in (complexsubquery1, complexsubquery2, complexsubquery3, complexsubquery4, complexsubquery5) )as unpvt group field
returns
field documentcount total ----------- ------------- ----------- 1 2 20 2 1 20 3 1 30 4 1 40 5 2 100
Comments
Post a Comment