计算视图中的字段

发布于 2025-01-12 06:32:16 字数 1201 浏览 0 评论 0原文

我的 MariaDB 数据库中有下表“数字”:

idnumber
125
241
33
473
538
641
712
814

现在我想创建一个视图,让我看到:

  • 第 1 列:所有可能的数字(不同)
  • 第 2 列:该数字出现的次数
  • 第 3 列:最后一个 ID 与该数字中的 ID 之间的 ID 数量。

这将导致这个视图:

numberoccurrencesIDdifferences1
315
1211
1410
2517
3813
4122
734所以

我开始于:

SELECT DISTINCT number FROM numbers 

然后在同一个表上进行左连接来计数,但是使查询变得非常慢(并且它没有按照我想要的方式工作)。您知道如何解决这个问题吗?预先非常感谢!

I have the following table "numbers" in my MariaDB database:

idnumber
125
241
33
473
538
641
712
814

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:

numberoccurrencesIDdifferences
315
1211
1410
2517
3813
4122
7314

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

后eg是否自 2025-01-19 06:32:16

您可以按数字分组并使用 COUNT() 聚合函数来获取列 occurrencesMAX() 窗口函数来获取列 >IDdifferences

SELECT number,
       COUNT(*) occurrences,
       MAX(MAX(id)) OVER () - MAX(id) IDdifferences
FROM numbers
GROUP BY number
ORDER BY number;

如果 ids 之间存在间隙:

SELECT number,
       COUNT(*) occurrences,
       MAX(MAX(rn)) OVER () - MAX(rn) IDdifferences
FROM (SELECT *, ROW_NUMBER() OVER (ORDER BY id) rn FROM numbers) t
GROUP BY number
ORDER BY number;

请参阅 演示

Yo can group by number and use COUNT() aggregate function to get the column occurrences and MAX() window function to get the column IDdifferences:

SELECT number,
       COUNT(*) occurrences,
       MAX(MAX(id)) OVER () - MAX(id) IDdifferences
FROM numbers
GROUP BY number
ORDER BY number;

If there are gaps between the ids:

SELECT number,
       COUNT(*) occurrences,
       MAX(MAX(rn)) OVER () - MAX(rn) IDdifferences
FROM (SELECT *, ROW_NUMBER() OVER (ORDER BY id) rn FROM numbers) t
GROUP BY number
ORDER BY number;

See the demo.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文