MySQL将行作为列

时间:2018-03-16 18:01:27

标签: mysql group-by

我有以下查询

SELECT Date(snapshot_date)
     , sku
     , detailed_disposition
     , sum(quantity) 
  FROM clabDevelopment.FBAInventory_fba_history
 group 
    by Date(snapshot_date)
     , sku
     , detailed_disposition;

它会产生这些结果enter image description here

是否可以将SKU保持在一行上,并将数量显示为列

   Date      | SKU     |  SELL_QTY |  CUS_DMG_QTY  |  WRE_DMG_QTY  |
2018-03-14     t-bnr       504          2                1

1 个答案:

答案 0 :(得分:0)

对当前结果使用条件聚合

SELECT date, sku
       SUM(case when detailed_disposition = 'sellable'  then Total else 0 end) as sellable,
       SUM(case when detailed_disposition = 'defective' then Total else 0 end) as damage,
       SUM(case when detailed_disposition = 'warehouse' then Total else 0 end) as warehouse
FROM ( 
    SELECT Date(snapshot_date) as date
         , sku
         , detailed_disposition
         , sum(quantity)  as Total
      FROM clabDevelopment.FBAInventory_fba_history
     group 
        by Date(snapshot_date)
         , sku
         , detailed_disposition
     ) as T
GROUP BY date, sku