【发布时间】:2014-07-10 16:42:31
【问题描述】:
几个月前,当一家著名的 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..
如何编写查询以查找每行的订单总数 count=1,2,3... 等
我对这个问题的想法是首先子查询每个 order_id 的 line_id 计数。
然后选择子查询以及值列表作为第二列,范围从 1 到 max(lines_id per order)
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 到 max(每个订单的行数)的数字序列也是错误的。
有什么建议吗?
提前致谢!
【问题讨论】:
-
这个问题有点含糊,“求每行计数中的订单数”是什么意思?
-
这意味着,给定一个 order_id 和 line_id 的表。您首先必须找到 count(order_id),然后找到 count(order_id) 有多少 line = 1、=2、=3.. 等等!例如,如果 10 个 order_id 的 count(order_id) = 1,则 5 个 order_id 的 count(order_id)=2,而 3 个 order_id 的 count(order_id) =3。那么输出是:count(order_id), line || 10, 1 || 5, 2 || 3, 3
-
如果你不知道 MySQL 和 SQL Server 之间的区别,那么你就不能胜任这份工作
-
@podiluska,根据您的声誉,我知道您擅长 SQL,但老实说,我被这个问题困住了。因此,如果您试图根据您的知识羞辱我,那么我无话可说。我没有得到那份工作,因为那时我还没有准备好。此外,我在工作中使用 SQL Server,但首先学习了 MySQL。事实上,我的 PC 上只安装了 MySQL。最后感谢您的意见以及投票否决我。
-
@user1489597 关键是 SQL 是特定于平台的。如果您想要通用 SQL,请不要使用特定标签,否则您会惹恼多组不同的人。
标签: sql