从mysql表中选择第二个最小值()或第二个最小值
我想知道如何从mysql表中选择第二个最小值,分组在非数字列上。如果我有一张这样的桌子:从mysql表中选择第二个最小值()或第二个最小值,mysql,sql,database,Mysql,Sql,Database,我想知道如何从mysql表中选择第二个最小值,分组在非数字列上。如果我有一张这样的桌子: +----+----------+------------+--------+------------+ | id | customer | order_type | amount | created_dt | +----+----------+------------+--------+------------+ | 1 | 1 | web |
+----+----------+------------+--------+------------+
| 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 |
+----+----------+------------+--------+------------+
我想统计每个月/年的第二批订单数量。我还有一个customer表,它是customer 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 |
+-------+------+---------------+
实现这一点的一种方法 选择年创建年、月创建月、计数*秒订单 从…起 选择created_dt, @注册护士:=IF@c=客户,@rn+1,1rn, @c:=顾客 从订单交叉连接 选择@c:=NULL,@rn:=1 我 其中订单类型='web' 按客户、id订购 Q 其中rn=2 按年份分组创建,按月份创建 按年、按月订购 这是一个演示 输出: +------+-------+---------------+ | year | month | second_orders | +------+-------+---------------+ | 2017 | 1 | 1 | | 2017 | 2 | 1 | | 2017 | 3 | 1 | +------+-------+---------------+
你能解释一下“二次订单”是什么意思吗?我想OP是指一个客户一个月内至少订购两次的次数。@vkp是客户第二次订购的次数。从样本数据集中,17年1月有一个二次订单,17年2月有一个二次订单,17年3月有一个二次订单。你能根据样本数据发布所需的输出吗?@peterm更新了我的问题以显示所需的结果。另外,感谢你向我展示dbfiddle,我知道jsfiddle,但不知道有db版本!