Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Calculate fields in a view

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

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;

See the demo.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading