Have a table(test):
color | count_var |
--------------------+-------------+
red & white | 15 |
black & white | 10 |
black | 10 |
black & white | 15 |
red & white | 15 |
SELECT MAX(mycount) as mode
FROM (SELECT COUNT(*) as mycount, count_var
FROM test
GROUP BY count_var) as t;
Have the result
mode
------
3
What I need at first? The result like
mode | count_var
------+----------
3 | 15
Then I need to insert this result at another table to the field with type integer[].
The inserting result should be {3,15}
How can I do this?
Well, you can do:
SELECT ARRAY[num_mycount, mycount]
FROM (SELECT count_var, COUNT(*) as mycount,
COUNT(*) OVER (PARTITION BY COUNT(*)) as num_mycount
FROM test
GROUP BY count_var
) t
ORDER BY mycount DESC
FETCH FIRST 1 ROW ONLY;
Amusingly, I don't think I have ever used COUNT(*) OVER (PARTITION BY COUNT(*))
before. I've gotten used to mixing window functions with aggregations, but I can imagine some people will find this a little confusing.
The first COUNT(*)
is a window function counting the number of rows in a partition of the result set -- that is, after the aggregation. The second is the aggregation COUNT(*)
. So the effect is to count the number of values that have the same count after the aggregation.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.