SQL查找每个行数的订单数

时间:2014-07-10 06:54:31

标签: sql

几个月前,当他们采访我的时候,我有一个着名的IT公司的SQL问题,我从来没有想到它。

订单可以包含多行 - 例如,如果客户订购了Cookie,

巧克力和面包,这将在一个订单中计为3行。问题

是查找每个行数的订单数。此查询的输出

将是100个订单有1行,70个订单有2行,30个有3个

行,等等。该表有两列 - order_id和line_id

 Sample Data:
 order_id   line_id
 1      cookies
 1      chocolates
 1      bread
 2      cookies
 2      bread
 3      chocolates
 3      cookies
 4      milk

所需的输出:

 orders line
 1       1
 2       2
 1       3

所以一般来说,我们有一个非常大的数据集,每个order_id的line_id可以从1到无穷大(从理论上讲)。

 The desired output for the general case is:

 orders line
 100    1
  70    2
  30    3
  etc..

如何编写查询以查找每行计数的订单总数= 1,2,3 ...等等

我对这个问题的想法是首先查询每个order_id的line_id计数。

然后选择子查询以及值列表作为第二列,范围从1到最大(每个订单的lines_id)

 Test Data:

 create table data
 (
 order_id int,
 line_id char(50)   
 );


 insert into data
 values(1,  'cookies'),
 (1,    'chocolates'),
 (1,    'bread'), 
 (2,    'bread'),
 (2,    'cookies'),
 (3,    'chocolates'),
 (3,    'cookies'),
 (4,    'milk');


 Since order_id=1 has 3 lines,
 order_id=2 has 2 lines,
 order_id=3 has 2 lines,
 order_id=4 has 1 line.

 Thus it yield our solution:

 orders line
 1       1
 2       2
 1       3

 This is because both order_id = 2 and 3 has 2 lines. So it would mean 2 orders has line = 2.

到目前为止,我有:

 select lines,
 sum(case when orders_per_line = '1' then 1 else 0),
 sum(case when orders_per_line = '2' then 1 else 0),
 sum(case when orders_per_line = '3' then 1 else 0)
 from(
 select lines, order_id, count(*) as orders_per_line from data
 where lines in ('1, '2', '3')
 group by order_id, lines
 )
 group by lines

我的查询错误,因为我只想要2列,并且还创建一系列从1到最大(每个订单行数)的数字也是错误的。

有什么建议吗?

提前致谢!

3 个答案:

答案 0 :(得分:1)

试试这个:

with a AS
(
SELECT 
    COUNT(order_id) AS Orders
FROM
    Table_1
GROUP BY
    Order_Id    
) 
SELECT 
    Orders,
    COUNT(*) AS line
FROM 
    a
    GROUP BY Orders 

答案 1 :(得分:1)

试试这个:

Select Count(*) as Orders, Lines from (
    Select order_id, Count(*) as Lines from data group by order_id
)query group by Lines

例如,请查看此sqlfiddle

答案 2 :(得分:0)

基本上,它只计算order_id重复的次数:

SELECT order_id, count(order_id) FROM data GROUP BY order_id