2

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

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

  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 查询来完成此操作。

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

*

因此,在查看下面的评论后,我想我最好只包含我现在正在使用的实际代码。

我的问题:我需要一个查询中两个选择语句的结果,我只是不知道该怎么做。所以总共会有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
4

1 回答 1

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小提琴

分析函数为您提供了一些可以加入的ROW_NUMBER()东西,并且通过使用 FULL OUTER JOIN,如果一种颜色的行数多于另一种颜色,这并不重要。


啊,现在您已经在代码中添加了不同的列名!原理应该完全一样;您当前的查询成为我在这里的子查询。

于 2013-09-11T19:55:05.883 回答