【问题标题】:grouping db2 results of multiple rows to give columns for the different results将多行的 db2 结果分组以给出不同结果的列
【发布时间】:2019-10-25 17:40:09
【问题描述】:

我有一个相当简单的查询,可以在 DB2 中正确执行,但是我在弄清楚如何对结果进行分组以给我 2 列时遇到了麻烦 替换 2 个不同行的列的值。换句话说,对于每个产品,我得到 2 行(一个是有效价格,一个是临时价格) 但我想这样做,以便我得到一个不同的产品行,其中每个价格类型和价格都有一列

查询:

    select distinct grouping, body, fabric,color,thread,detail, category,p.priceType,p.price
    from ordering offs
    inner join pricing p
    on offs.body = p.bodyp
    where priceType in ('Active','Temporary')
    and offs.category in ('A','B','C');

我得到了什么:

    grouping  |  body  |  fabric  |  color  |  thread  |  detail  |  category  |  p.priceType  |  price
    -----------------------------------------------------------------------------------------------------
    ABC          123        1234       Blue     1.1       1           TEXTILE       Active          594.00
    ABC          123        1234       Blue     1.1       1           TEXTILE       Temporary       560.00
    ABC          123        1234       Red      0.5       0           TEXTILE       Active          584.00
    ABC          123        1234       Red      0.5       0           TEXTILE       Temporary       550.00
    ABC          123        1234       Grn      3.3       12          TEXTILE       Active          594.00
    ABC          123        1234       Grn      3.3       12          TEXTILE       Temporary       560.00

我想得到什么:

    grouping  |  body  |  fabric  |  color  |  thread  |  detail  |  category  |  ActivePrice  |  TemporaryPrice
    ------------------------------------------------------------------------------------------------------------
    ABC          123        1234       Blue     1.1       1           TEXTILE       594.00            560.00
    ABC          123        1234       Red      0.5       0           TEXTILE       584.00            550.00
    ABC          123        1234       Grn      3.3       12          TEXTILE       594.00            560.00

【问题讨论】:

标签: sql db2 db2-400


【解决方案1】:

一个简单的方法使用条件聚合:

select grouping, body, fabric, color, thread, detail, category, 
      max(case when p.priceType = 'Active' then p.price end) as active_price,
      max(case when p.priceType = 'Temporary' then p.price end) as temporary_price
from ordering offs inner join
     pricing p
     on offs.body = p.bodyp
where priceType in ('Active', 'Temporary') and
      offs.category in ('A', 'B', 'C')
group by grouping, body, fabric, color, thread, detail, category;

【讨论】:

  • 这似乎仍然给了我单独的行,只有一个会处于活动状态,而 temp 将为空,反之亦然
  • 我认为这是因为我按价格分组,这在两行之间创建了一个区别
  • @TomN。 . . .我从SELECT 中删除了这些列,但没有从GROUP BY 中删除。现在已修复。
猜你喜欢
  • 2012-06-02
  • 1970-01-01
  • 1970-01-01
  • 2017-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-25
相关资源
最近更新 更多