简体   繁体   English

从列中计算7和0的出现次数

[英]Count the number of occurrence of 7 and 0 from the column

I have a data like below format, now I want to count the occurrences of '7' and '0', like how many time it's showed up in the table from 'vi' column ?? 我有一个类似于以下格式的数据,现在我想计算“ 7”和“ 0”的出现次数,例如“ vi”列中的表格中显示了多少次?

ci vi 
1  7  
2  0  
3  0  
4  7  
5  7
6  10
7  15
8  0
9  16
10 7
11 0
12 35

thanks in advance 提前致谢

Try this 尝试这个

  ;WITH CTE(ci ,vi )
AS
(
SELECT 1  ,7   UNION ALL
SELECT 2  ,0   UNION ALL
SELECT 3  ,0   UNION ALL
SELECT 4  ,7   UNION ALL
SELECT 5  ,7   UNION ALL
SELECT 6  ,10  UNION ALL
SELECT 7  ,15  UNION ALL
SELECT 8  ,0   UNION ALL
SELECT 9  ,16  UNION ALL
SELECT 10 ,7   UNION ALL
SELECT 11 ,0   UNION ALL
SELECT 12 ,35 
)
SELECT vi,COUNT(vi) Occurence
FROM CTE
WHERE vi IN (7,0) -- Specific values count Required use this where condition else remove
GROUP BY vi

Result 结果

vi  Occurence
--------------
0      4
7      4

MS SQL Can be achieved by GROUP BY 可以通过GROUP BY实现MS SQL

select vi, count(1) [COUNT] from @table1
group by vi
having vi in (7,0)

DEMO 演示

I think you can use sum and case-when like: 我认为您可以使用sumcase-when例如:

select
     sum(case when vi = 7 then 1 else 0 end) as [7Count],
     sum(case when vi = 0 then 1 else 0 end) as [0Count]
from table

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

相关问题 SQL计数按列发生 - SQL count occurrence by column 如何计算4列中的出现次数 - How to count the number of occurrence in 4 columns 编写一个查询(最好在 sqlalchemy 中)以计算在 postgres 表中由另一列分组的列中唯一值的出现次数 - Write a query (preferably in sqlalchemy) to count number of occurrence of unique values in a column grouped by another column in a postgres table 如何计算列值的出现次数但没有GROUP BY(不是不同的值)mysql - How to count the number of occurrence of column values but without GROUP BY (not distinct values) mysql 根据其他三个列的出现将列添加为 int 计数。 如何使用 ROW_NUMBER 插入? - Add column as int count based on the occurrence of three other columns. How to use ROW_NUMBER with insert? 计算几列中值出现的次数 - Count number of occurrence of a value in several columns 计数表中值的连续出现次数 - Count Number of Consecutive Occurrence of values in Table 如何计算varchar中指定char的出现次数 - How to count number of occurrence of specify char in varchar 更改列值取决于出现次数 - Change the column value depends on occurrence count 有没有一种方法可以计算SQL中多列值的出现? - Is there a way to count occurrence of values of multiple column in SQL?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM