【问题标题】:SELECT from sql 2 cols in 1 table group by date按日期从 1 个表组中的 sql 2 列中选择
【发布时间】:2020-07-25 07:42:57
【问题描述】:

我的 select 语句使用 1 个表中的 2 个列并按日期对数据进行分组时遇到了一些问题。 我拥有的数据喜欢这个屏幕:

和我想要的结果:

有人可以帮忙吗?

【问题讨论】:

  • 请用您正在使用的数据库标记您的问题:mysql、oracle、postgresql...?
  • 你能详细说明结果吗?

标签: mysql sql select group-by pivot


【解决方案1】:

你可以做条件聚合:

select 
    date_format(date, '%Y-%m-01') date_month,
    sum(`close` > `open`) uptime,
    sum(`close` < `open`) downtime,
    sum(`close` = `open`) equaltime
    stock_id
from mytable
group by date_month, stock_id

请注意,我添加了一个额外的查询 do count days 其中close 等于open。

【讨论】:

    【解决方案2】:

    您可以使用right() 从日期中提取您需要的月份

    select
        right(date, 6) as month,
        sum(case when change > 0 then 1 else 0 end) as up_times,
        sum(case when change < 0 then 1 else 0 end) as down_times,
        stock_id
    from yourTable
    group by
        right(date, 6),
        stock_id
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-23
      • 2018-03-30
      相关资源
      最近更新 更多