繁体   English   中英

将多行的 db2 结果分组以给出不同结果的列

[英]grouping db2 results of multiple rows to give columns for the different results

我有一个相当简单的查询,可以在 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

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

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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM