将行转换为列,将列转换为行而无需透视

时间:2018-07-19 09:40:15

标签: sql

ProductCode YTMAch  YTMTg   MTDTg   YTDPer  MTDPer
PrimaxX         0   0         0        0    0
SuperGrip       0   0         0        0    0
WC              0   0         0        0    0
WP              0   0         0        0    0

我想将此行转换为列,并将列转换为行

2 个答案:

答案 0 :(得分:2)

一种方法是使用<background> <band height="702" splitType="Stretch"> </band> </background> <title> <band height="2" splitType="Stretch"/> </title> <pageHeader> <band height="2" splitType="Stretch"/> </pageHeader> <columnHeader> <band height="2" splitType="Stretch"/> </columnHeader> <detail> <band height="830" splitType="Stretch"> <background> <band height="702" splitType="Stretch"> <textField> <reportElement mode="Transparent" x="0" y="0" width="0" height="0" forecolor="#DFDFDF"> <printWhenExpression>true</printWhenExpression> </reportElement> </textField> </band> </background>

case

答案 1 :(得分:0)

在标准SQL中,您可以对每列使用UNION ALL和selects。
但这是一个比较罗word的方法。

诸如Ajay的MS Sql Server解决方案之类的数据库特定方法应该更简洁。

例如:

select Metric, 
sum(case when ProductCode = 'PrimaxX' then Value end) as PrimaxX,
sum(case when ProductCode = 'SuperGrip' then Value end) as SuperGrip,
sum(case when ProductCode = 'WC' then Value end) as WC,
sum(case when ProductCode = 'WP' then Value end) as WP
from
(
  select 'YTMAch' as Metric, ProductCode, YTMAch as Value from yourtable
  union all 
  select 'YTMTg', ProductCode, YTMTg from yourtable
  union all 
  select 'MTDTg', ProductCode, MTDTg from yourtable
  union all 
  select 'YTDPer', ProductCode, YTDPer from yourtable
  union all 
  select 'MTDPer', ProductCode, MTDPer from yourtable
) q
group by Metric;
相关问题