【问题标题】:I can't make a manually output of my table using mysql我无法使用 mysql 手动输出我的表
【发布时间】:2020-07-27 15:53:03
【问题描述】:

我有交易表,

id transaction_date status
1  2020-01-01       Shipped
2  2020-02-01       Shipped
3  2020-02-01       Cancelled

我希望将其转换为 excel 中的数据透视表,如下所示

Date       SHIPPED CANCELLED PROCESSING
2020-01-01 1       0         0
2020-02-01 1       1         0

我完全没有办法解决这个问题。我应该使用什么功能?

【问题讨论】:

  • 可以使用case 处理条件,但语法比下面的sum(status='whatever') 更笨拙

标签: mysql sql date pivot


【解决方案1】:

您可以使用聚合,如:

select
  date,
  sum(status = 'Shipped') as shipped,
  sum(status = 'Cancelled') as cancelled,
  sum(status = 'Processing') as processing
from t
group by date

在 MySQL 中,谓词(通常计算为布尔值)也计算为 INT0 为 false,1 为 true。

【讨论】:

    【解决方案2】:

    使用条件聚合:

    select
        date,
        sum(status = 'Shipped')   shipped,
        sum(status = 'Cancelled') cancelled,
        sum(status = 'Processing') processing
    from mytable
    group by date
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-02
      • 1970-01-01
      • 1970-01-01
      • 2021-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多