我如何 select 内连接中的第二个最小值?
How can I select the second minimal value within a inner join?
我有这个问题
select c.id, c.name, c.email, c.totalpets, min(p.date_created) as first_order,
min(p.weight) as min_weight_bought,
max(p.weight) as max_weight_bought,
count(p.ordernumber) as total_orders
from orders p
inner join customers c
on p.customer_id = c.id
where p.approved = 1
and c.totalpets >= 1
group by c.id
having total_orders > 1
注意 first_order 给了我该行的第一个结果,对吧?我正在尝试获得客户的第一笔订单和客户的第二笔订单。我怎样才能在这个内部连接中做到这一点?
谢谢
SELECT c1.id,
c1.name,
c1.email,
c1.totalpets,
p1.date_created
FROM orders p1
INNER JOIN customers c1
ON p1.customer_id = c1.id
WHERE
(
SELECT COUNT(*)
FROM orders p2
INNER JOIN customers c2
ON p2.customer_id = c2.id
WHERE c2.id = c1.id AND p2.date_created <= p1.date_created
) <= 2
ORDER BY c1.id;
这是一个 运行 演示,其中显示了上述查询(和简化数据集)的简化版本:
我有这个问题
select c.id, c.name, c.email, c.totalpets, min(p.date_created) as first_order,
min(p.weight) as min_weight_bought,
max(p.weight) as max_weight_bought,
count(p.ordernumber) as total_orders
from orders p
inner join customers c
on p.customer_id = c.id
where p.approved = 1
and c.totalpets >= 1
group by c.id
having total_orders > 1
注意 first_order 给了我该行的第一个结果,对吧?我正在尝试获得客户的第一笔订单和客户的第二笔订单。我怎样才能在这个内部连接中做到这一点?
谢谢
SELECT c1.id,
c1.name,
c1.email,
c1.totalpets,
p1.date_created
FROM orders p1
INNER JOIN customers c1
ON p1.customer_id = c1.id
WHERE
(
SELECT COUNT(*)
FROM orders p2
INNER JOIN customers c2
ON p2.customer_id = c2.id
WHERE c2.id = c1.id AND p2.date_created <= p1.date_created
) <= 2
ORDER BY c1.id;
这是一个 运行 演示,其中显示了上述查询(和简化数据集)的简化版本: