Over()函数不能覆盖表中的所有行
我正在使用MySQL练习SQL,并在SQL中遇到了一种奇怪的行为。假设我有一张桌子:
Delivery table:
+-------------+-------------+------------+-----------------------------+
| delivery_id | customer_id | order_date | customer_pref_delivery_date |
+-------------+-------------+------------+-----------------------------+
| 1 | 1 | 2019-08-01 | 2019-08-02 |
| 2 | 5 | 2019-08-02 | 2019-08-02 |
| 3 | 1 | 2019-08-11 | 2019-08-11 |
| 4 | 3 | 2019-08-24 | 2019-08-26 |
| 5 | 4 | 2019-08-21 | 2019-08-22 |
| 6 | 2 | 2019-08-11 | 2019-08-13 |
+-------------+-------------+------------+-----------------------------+
我的查询:
SELECT COUNT(*) as imm, count(*) over() as all_t
FROM
Delivery
WHERE order_date = customer_pref_delivery_date
结果:
+-----+-------+
| imm | all_t |
+-----+-------+
| 2 | 1 |
+-----+-------+
我希望 over()函数将覆盖整个桌子,在这种情况下,返回6,但由于某种原因,它只会返回1。有这种行为的解释吗?
i am practising SQL with MySQL and encounter a strange behaviour in SQL. Say i have a table like this:
Delivery table:
+-------------+-------------+------------+-----------------------------+
| delivery_id | customer_id | order_date | customer_pref_delivery_date |
+-------------+-------------+------------+-----------------------------+
| 1 | 1 | 2019-08-01 | 2019-08-02 |
| 2 | 5 | 2019-08-02 | 2019-08-02 |
| 3 | 1 | 2019-08-11 | 2019-08-11 |
| 4 | 3 | 2019-08-24 | 2019-08-26 |
| 5 | 4 | 2019-08-21 | 2019-08-22 |
| 6 | 2 | 2019-08-11 | 2019-08-13 |
+-------------+-------------+------------+-----------------------------+
My query:
SELECT COUNT(*) as imm, count(*) over() as all_t
FROM
Delivery
WHERE order_date = customer_pref_delivery_date
Result :
+-----+-------+
| imm | all_t |
+-----+-------+
| 2 | 1 |
+-----+-------+
I expect the over() function will cover the whole table, and in this case return 6, but it only returns 1, for some reason. Is there an explanation for this behaviour?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
窗口函数:
在查询结果上操作:
只有1行(带1列),这就是为什么您获得1的原因。
我相信您正在寻找的是条件汇总:
请参阅
The window function:
operates on the results of the query:
which is only 1 row (with 1 column) and this is why you get 1 as result.
I believe what you are looking for is conditional aggregation:
See the demo.
选择计数(*)
计算满足WHERE子句中条件的行。有两个这样的行。具有聚合功能的查询,但没有返回单行的组来报告计数。然后,窗口函数适用于该结果集,并计数1行。换句话说,窗口函数适用于聚集后的行集已减少行的数量。
您可以通过省略汇总来测试这一点:
或者如果没有哪个条款的条件,它将返回六行组中的每一个的行计数:
The
SELECT COUNT(*)
counts rows that satisfy the conditions in the WHERE clause. There are two such rows.The query with an aggregate function but no GROUP BY returns a single row, to report the count. The window function then applies to that result set, and counts 1 row. In other words, window functions apply to the set of rows after aggregation has reduced the number of rows.
You can test this by omitting the aggregation:
Or without the conditions of the WHERE clause, it returns the count of rows for each of the set of six rows: