【问题标题】:Separate group_concat() result单独的 group_concat() 结果
【发布时间】:2013-08-22 12:21:14
【问题描述】:

我正在尝试获取客户的 5 个最新订单时间:

SET SESSION group_concat_max_len = 99;
select o.customer_id, substring_index(m.orders,',', 1) as order1,
    (case when numc >=2 then substring_index(substring_index(m.orders, ',', 2), ',', -1)end) as order2,
    (case when numc >=3 then substring_index(substring_index(m.orders, ',', 3), ',', -1)end) as order3,
    (case when numc >=4 then substring_index(substring_index(m.orders, ',', 4), ',', -1)end) as order4,
    (case when numc >=5 then substring_index(substring_index(m.orders, ',', 5), ',', -1)end) as order5
    from orders o,
         (select group_concat(date order by date desc) as orders, count(*) as numc
          FROM orders) m
where country_id='27' 
group by customer_id

但它会为所有客户返回我的 sysdate。

我哪里做错了?

【问题讨论】:

  • 顶级查询中没有聚合函数时为什么会有GROUP BY customer_id
  • 我的意思是 o.customer_id,我的错 :)
  • 那是一回事。为什么不聚合时要分组?只有子查询聚合,但不分组。

标签: mysql group-concat


【解决方案1】:

我不确定您所说的“所有客户的 sysdate”是什么意思。但是,join 并没有达到您的预期。

只做一次聚合:

select o.customer_id, substring_index(group_concat(date order by date desc),',', 1) as order1,
    (case when count(*) >=2 then substring_index(substring_index(group_concat(date order by date desc), ',', 2), ',', -1)end) as order2,
    (case when count(*) >=3 then substring_index(substring_index(group_concat(date order by date desc), ',', -1)end) as order3,
    (case when count(*) >=4 then substring_index(substring_index(group_concat(date order by date desc), ',', 4), ',', -1)end) as order4,
    (case when count(*) >=5 then substring_index(substring_index(group_concat(date order by date desc), ',', 5), ',', -1)end) as order5
    from orders o
where country_id='27' 
group by customer_id

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-22
    • 2016-08-08
    • 1970-01-01
    • 2012-04-28
    相关资源
    最近更新 更多