客户订购表-sql

时间:2016-01-23 11:27:23

标签: sql

我试着编写sql查询,它会在下面给我这个输出。你可以看到我添加的表格。提前致谢

2 个答案:

答案 0 :(得分:1)

根据OP

更新了答案

这将只为您提供最多订单数customer_id。由于缺乏分析功能,在MySQL中形成有点复杂的查询。但这应该工作正常。

select t.* from 
    (select o.customer_id,
    count(*) as no_of_orders
    from orders o
    group by o.customer_id) t
where 
t.no_of_orders =
    (
    select max(no_of_orders) from 
        (select o.customer_id,
        count(*) as no_of_orders
        from orders o
        group by o.customer_id
        )t2
    )

在此处查看演示

http://sqlfiddle.com/#!9/18726a/12

上一个答案:

这会奏效。如果客户没有Left Join

0将确保计算order
select c.customer_id,count(o.order_id) as NO_OF_ORDERS
from customers c
left join orders o
on c.customer_id=o.customer_id
group by c.customer_id

在此处查看演示

http://sqlfiddle.com/#!9/3c19e/4

答案 1 :(得分:0)

SQL的大多数方言都支持ANSI标准行号函数。您可以将它们用于此目的。请注意,join不是必需的:

select customer_id, cnt
from (select o.customer_id, count(*) as cnt,
             max(count(*)) over () as maxcnt
      from orders o
      group by o.customer_id
     ) o
where cnt = maxcnt;