[英]How get the most frequent value in an ARRAY in sql?
I´ma newbie in SQL.我是 SQL 新手。
I have built an array where I have been storing the values that I have been collecting in a loop and dividing them by other value.我已经建立了一个数组,我一直在其中存储我在循环中收集的值并将它们除以其他值。
The array has the correct values.该数组具有正确的值。
Now I would need to get the most repeated value in this array.现在我需要得到这个数组中重复次数最多的值。
Is this possible with SQL?这可以用 SQL 实现吗? My environment is Oracle 11.
我的环境是 Oracle 11。
This is the array:这是数组:
type array_type is varray(100) of NUMBER(10);
loop_results array_type := array_type();
The values:价值:
1: 906450
2: 906450
3: 306449
4: 906446
5: 306450
6: 906447
7: 306449
8: 306448
9: 306448
10: 306450
Thanks for your time.谢谢你的时间。
First of all arrays are a part of pl/sql.首先,数组是 pl/sql 的一部分。 Likewise try the below.
同样试试下面的。 The below would be somewhat easy using a temporary table.
使用临时表,下面的内容会有些容易。
Create table sample(value1
number(10));
Declare
type array_type is varray(100) of
NUMBER(10);
loop_results array_type := array_type();
Max varchar2(20);
begin
for i in 1..loop_results.length
loop
Insert into sample values
(loop_results(i)) ;
End loop
Select value1 into max from(Select
Value1,
count(*)
from sample order by count(*) desc
Group by value1) where rownum=1;
dbms_output.put_line(max) ;
End
You can do it in SQL if the type is declared in the SQL scope:如果类型在 SQL 范围内声明,您可以在 SQL 中执行此操作:
CREATE TYPE array_type is varray(100) of NUMBER(10);
Then (Oracle 12+ solution)然后(Oracle 12+ 解决方案)
SELECT COLUMN_VALUE,
COUNT(*)
FROM TABLE(
array_type(
906450,
906450,
306449,
906446,
306450,
906447,
306449,
306448,
306448,
306450
)
)
GROUP BY COLUMN_VALUE
ORDER BY COUNT(*) DESC
FETCH FIRST 1 ROW WITH TIES;
or (for earlier versions, you can use analytic functions):或(对于早期版本,您可以使用解析函数):
SELECT value,
cnt
FROM (
SELECT COLUMN_VALUE AS value,
COUNT(*) As cnt,
DENSE_RANK() OVER ( ORDER BY COUNT(*) DESC ) AS rnk
FROM TABLE(
array_type(
906450,
906450,
306449,
906446,
306450,
906447,
306449,
306448,
306448,
306450
)
)
GROUP BY COLUMN_VALUE
)
WHERE rnk = 1;
Outputs all the values that are tied for the highest frequency:输出与最高频率相关的所有值:
\nCOLUMN_VALUE |COLUMN_VALUE | COUNT(*)
数数(*)\n-----------: |
-----------: | -------:
-------:\n 306449 |
306449 | 2
2\n 906450 |
906450 | 2
2\n 306450 |
306450 | 2
2\n 306448 |
306448 | 2
2\n
db<>fiddle Oracle 18 or Oracle 11 db<>fiddle Oracle 18或Oracle 11
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.