从mysql表

时间:2017-06-07 14:59:10

标签: mysql sql database

我想知道如何从mysql表中选择第二个最小值,并将其分组在非数字列上。如果我有一个看起来像这样的表:

    +----+----------+------------+--------+------------+
    | id | customer | order_type | amount | created_dt |
    +----+----------+------------+--------+------------+
    |  1 |        1 | web        |      5 | 2017-01-01 |
    |  2 |        1 | web        |      7 | 2017-01-05 |
    |  3 |        2 | web        |      2 | 2017-01-07 |
    |  4 |        3 | web        |      2 | 2017-02-01 |
    |  5 |        3 | web        |      3 | 2017-02-01 |
    |  6 |        2 | web        |      5 | 2017-03-15 |
    |  7 |        1 | in_person  |      7 | 2017-02-01 |
    |  8 |        3 | web        |      8 | 2017-01-01 |
    |  9 |        2 | web        |      1 | 2017-04-01 |
    +----+----------+------------+--------+------------+

我想计算每个月/每年的第二个订单数量。我还有一个客户表(客户ID来自哪里)。通过查询,我可以通过客户的创建日期找到超过至少2个订单的客户数量

select date(c.created_dt) as create_date, count(c.id) 
from customer c 
where c.id in 
  (select or.identity_id 
  from orders or 
  where 
    (select count(o.created_dt) 
    from orders o 
    where or.customer = o.customer and o.order_tpe in ('web')
    ) > 1
  ) 
group by 1;

然而,这个结果给了客户创建的日期,而我似乎无法弄清楚如何按日期查找第二个订单的数量。 根据以上数据,我希望看到的所需输出是:

    +-------+------+---------------+
    | month | year | second_orders |
    +-------+------+---------------+
    |  1    | 2017 | 1             |
    |  2    | 2017 | 1             |
    |  3    | 2017 | 1             |
    +-------+------+---------------+

1 个答案:

答案 0 :(得分:1)

解决此问题的一种方法

SELECT YEAR(created_dt) year, MONTH(created_dt) month, COUNT(*) second_orders
  FROM (
    SELECT created_dt,
           @rn := IF(@c = customer, @rn + 1, 1) rn,
           @c := customer
      FROM orders CROSS  JOIN (
        SELECT @c := NULL, @rn := 1
      ) i
     WHERE order_type = 'web'
     ORDER BY customer, id
  ) q
 WHERE rn = 2
 GROUP BY YEAR(created_dt), MONTH(created_dt)
 ORDER BY year, month

这是dbfiddle演示

输出:

+------+-------+---------------+
| year | month | second_orders |
+------+-------+---------------+
| 2017 |     1 |             1 |
| 2017 |     2 |             1 |
| 2017 |     3 |             1 |
+------+-------+---------------+