简体   繁体   English

使用单个 SQL 查询计算列中给定值列表的出现次数

[英]Count the occurrences of a given list of values in a column using a single SQL query

I would like to get the count of occurrences of a given list of values in a column using a single SQL query.我想使用单个 SQL 查询获取列中给定值列表的出现次数。 The operations must be optimised for performance.必须针对性能优化操作。

Please refer the example given below,请参考下面给出的例子,

Sample Table name - history示例表名称 - 历史

code_list代码列表
5lysgj 5lysgj
627czl 627czl
1lqnd8 1lqnd8
627czl 627czl
dtrtvp dtrtvp
627czl 627czl
esdop9 esdop9
esdop9 esdop9
3by104 3by104
1lqnd8 1lqnd8

Expected Output预计 Output

Need to get the count of occurrences for these given list of codes 627czl, 1lqnd8, esdop9, aol4m6 in the format given below.需要以下面给出的格式获取这些给定代码列表 627czl、1lqnd8、esdop9、aol4m6 的出现次数。

code代码 count数数
627czl 627czl 3 3个
esdop9 esdop9 2 2个
1lqnd8 1lqnd8 2 2个
aol4m6 aol4m6 0 0

Method I tried in show below but the count of each input is shown as a new column using this query,我在下面显示的方法中尝试过,但每个输入的计数都显示为使用此查询的新列,

SELECT 
    sum(case when h.code_list = 'esdop9' then 1 else 0 end) AS count_esdop9,
    sum(case when h.code_list = '627czl' then 1 else 0 end) AS count_627czl,
    sum(case when h.code_list = '1lqnd8' then 1 else 0 end) AS count_1lqnd8,
    sum(case when h.code_list = 'aol4m6' then 1 else 0 end) AS count_aol4m6
FROM history h;

Note - The number inputs need to be given in the query in 10 also the real table has millions of records.注意 - 需要在 10 中的查询中给出数字输入,真实表也有数百万条记录。

If i properly understand you need to get the count of occurrences for the following codes: 627czl , 1lqnd8 , esdop9 .如果我正确理解您需要获取以下代码的出现次数: 627czl1lqnd8esdop9

In this case you can try this one:在这种情况下,您可以试试这个:

SELECT code_list, count(*) as count_
  FROM history
 WHERE code_list in ('627czl','1lqnd8','esdop9')
 GROUP BY code_list
 ORDER BY count_ DESC;

dbfiddle小提琴手

If you need to get the count of occurrences for all codes you can run the following query:如果您需要获取所有代码的出现次数,您可以运行以下查询:

SELECT code_list, count(*) as count_
  FROM history
 GROUP BY code_list
 ORDER BY count_ DESC;

you can try to use GROUP BY Something like this你可以尝试使用 GROUP BY Something like this

SELECT code_list, COUNT(1) as 'total' ROM h GROUP by code_list order by 'total' ;

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

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