Home > Net >  Calculate fields in a view
Calculate fields in a view

Time:03-08

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!

CodePudding user response:

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.

  • Related