计算视图中的字段
我的 MariaDB 数据库中有下表“数字”:
id | number |
---|---|
1 | 25 |
2 | 41 |
3 | 3 |
4 | 73 |
5 | 38 |
6 | 41 |
7 | 12 |
8 | 14 |
现在我想创建一个视图,让我看到:
- 第 1 列:所有可能的数字(不同)
- 第 2 列:该数字出现的次数
- 第 3 列:最后一个 ID 与该数字中的 ID 之间的 ID 数量。
这将导致这个视图:
numberoccurrences | IDdifferences | 1 |
---|---|---|
3 | 1 | 5 |
12 | 1 | 1 |
14 | 1 | 0 |
25 | 1 | 7 |
38 | 1 | 3 |
41 | 2 | 2 |
73 | 4 | 所以 |
我开始于:
SELECT DISTINCT number FROM numbers
然后在同一个表上进行左连接来计数,但是使查询变得非常慢(并且它没有按照我想要的方式工作)。您知道如何解决这个问题吗?预先非常感谢!
I have the following table "numbers" in my MariaDB database:
id | number |
---|---|
1 | 25 |
2 | 41 |
3 | 3 |
4 | 73 |
5 | 38 |
6 | 41 |
7 | 12 |
8 | 14 |
Now I would like to create a view that lets me see:
- column 1: All possible numbers (distinct)
- column 2: the amount of occurrences of that number
- column 3: the amount of IDs between the last ID and the ID from that number.
That would result in this view:
number | occurrences | IDdifferences |
---|---|---|
3 | 1 | 5 |
12 | 1 | 1 |
14 | 1 | 0 |
25 | 1 | 7 |
38 | 1 | 3 |
41 | 2 | 2 |
73 | 1 | 4 |
So I started with:
SELECT DISTINCT number FROM numbers
and then a left join on the same table to count , but that makes the query verrrry slow (and it didn't work the way I wanted). Do you have any idea how to resolve this? Thanks a lot in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以按数字分组并使用
COUNT()
聚合函数来获取列occurrences
和MAX()
窗口函数来获取列>IDdifferences
:如果 ids 之间存在间隙:
请参阅 演示。
Yo can group by number and use
COUNT()
aggregate function to get the columnoccurrences
andMAX()
window function to get the columnIDdifferences
:If there are gaps between the ids:
See the demo.