简体   繁体   English

SQL 查询:统计表中不同值的数量

[英]SQL Query: Count the number of distinct values in a table

I am trying to create a SQL query to count the number of distinct values in a SQL table.我正在尝试创建一个 SQL 查询来计算 SQL 表中不同值的数量。 My table has 6 columns:我的表有 6 列:

n1  n2  n3  n4  n5  n6
______________________
3   5   7   9   11  20
3   7   11  15  17  20
3   15  26  28  30  40
15  26  30  40  55  56
3   4   5   9   15  17
17  20  26  28  30  40

And here's the result I am trying to get:这是我想要得到的结果:

  value  frequency
______________________
    3       4
    4       1
    5       2
    7       2
    9       2
    11      2       
    15      3
    17      3   
    20      3
    26      3
    28      2
    30      3
    40      3
    55      1
    56      1

So basically, I need the query to look at the whole table, take a note of each value that appears, and count the number of times that particular value appears.所以基本上,我需要查询来查看整个表,记下出现的每个值,并计算特定值出现的次数。

Use UNION ALL to get all the nX column values in 1 column and aggregate:使用UNION ALL获取 1 列中的所有nX列值并聚合:

select value, count(*) as frequency
from (
  select n1 as value from tablename union all
  select n2 from tablename union all
  select n3 from tablename union all
  select n4 from tablename union all
  select n5 from tablename union all
  select n6 from tablename 
) t
group by value

I would recommend cross apply for this purpose:为此,我建议cross apply

select v.n, count(*) as frequency
from t cross apply
     (values (n1), (n2), (n3), (n4), (n5), (n6)) v(n)
group by v.n;

cross apply , which implements a lateral join is more efficient than union all for unpivoting data. cross apply实现横向连接union all更有效地用于反透视数据。 This is particularly true if your "table" is really a view or complex query.如果您的“表”确实是一个视图或复杂查询,则尤其如此。

here is the beautiful use case of UNPIVOT if you are using SQL SERVER or ORACLE :如果您使用的是SQL SERVERORACLE ,这是UNPIVOT的漂亮用例:

SELECT 
  [value]
  , count(*) frequency 
FROM 
( select n1,n2,n3,n4,n5,n6 from tablename) p
UNPIVOT ([value] for nums in ( n1,n2,n3,n4,n5,n6 )) as unpvt
GROUP BY [value]
ORDER BY frequency DESC

which is more efficient than Union, if performance matters there.如果性能在那里很重要,这比 Union 更有效率。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM