结果中来自同一字段的多个列

时间:2013-09-11 19:39:50

标签: sql oracle pivot multiple-columns

我正在尝试查询我的数据库并返回具有来自同一字段的多个列的结果。

我的数据库中的数据可能如下所示:

  id,        price,       cost,       description,        color
  --------------------------------------------------------------        
  10,         99,          50,         bicycle,           blue
  15,         88,          45,         tricycle,          red
  18,         90,          48,         tricycle,          blue
  20,         95,          55,         bicycle,           red

我正在尝试编写一个查询来返回结果,这些结果会给我多个列来表示每种颜色的颜色为“蓝色”或“红色”以及它们的ID,价格,成本和描述,如下所示:

Blue, id, price, cost, description, Red, id, price, cost, description
blue, 10, 99,    50,   bicycle,     red, 15, 88,    45,   tricycle
blue, 18, 90,    48,   tricycle,    red, 20, 95,    55,   bicycle

重点是能够并排查看数据,一旦数据在Excel中,我就可以在数据透视表中轻松完成此操作,但我们正试图通过SQL查询来完成此任务。

非常感谢任何帮助,如果我能提供任何其他信息,请告诉我。

*

因此,在审核下面的评论后,我想也许我只是包含我正在使用的实际代码。

我的问题:我需要在一个查询中的两个select语句的结果我只是无法弄清楚如何做到这一点。所以总共会有7列

类别代码,丢失时间索赔计数,丢失时间发生损失,丢失时间索赔平均值,仅医疗索赔计数,仅医疗损失索赔,仅医疗索赔平均值

select distinct cm.class_code, count(cm.class_code) as "Lost Time Claim Count",
   round(sum(cf.Incurred_Total),0) as "Lost Time Incurred Loss",
   round((sum(cf.Incurred_Total)/count(cm.class_code)),0) as "Lost Time Claim Average",
   cm.claim_type_group

from claim_master cm left outer join
 claim_financial_view cf on cm.claim_master_id = cf.Claim_Master_Id

where cm.accident_date > to_date('31-Dec-2007','dd-mm-yyyy') and
  cm.accident_date < to_date('01-Jan-2013','dd-mm-yyyy') and
  cm.claim_type_group = 'L'

group by cm.class_code,
     cm.claim_type_group

Order by cm.class_code

__

select distinct cm.class_code, count(cm.class_code) as "Medical Only Claim Count",
   round(sum(cf.Incurred_Total),0) as "Medical Only Incurred Loss",
   round((sum(cf.Incurred_Total)/count(cm.class_code)),0) as "Medical Only Claim      Average",
   cm.claim_type_group

from claim_master cm left outer join
 claim_financial_view cf on cm.claim_master_id = cf.Claim_Master_Id

where cm.accident_date > to_date('31-Dec-2007','dd-mm-yyyy') and
  cm.accident_date < to_date('01-Jan-2013','dd-mm-yyyy') and
  cm.claim_type_group = 'M'

group by cm.class_code,
     cm.Claim_Type_Group

Order by cm.class_code

1 个答案:

答案 0 :(得分:1)

由于您的数据之间没有任何关系,我认为创建一个数据最简单。这可能是许多可能的解决方案之一:

select a.color as blue, a.id as idb, a.price as priceb
     , a.cost as costb, a.description as descb
     , b.color as red, b.id as idr, b.price as pricer
     , b.cost as costr, b.description as descr
  from ( select x.*, row_number() over ( order by id ) as rn
           from my_table x
          where color = 'blue'
                ) a
  full outer join ( 
         select x.*, row_number() over ( order by id ) as rn
            from my_table x
           where color = 'red'
                 ) b
    on a.rn = b.rn

SQL Fiddle

ROW_NUMBER()分析函数为您提供了连接的功能,并且通过使用FULL OUTER JOIN,如果一种颜色的行数多于另一种颜色,则无关紧要。


Ach,现在你在代码中添加了不同的列名!原则应该完全一样;您当前的查询将成为我在此处的子查询。