Sql 统计表中特定值的出现次数的步骤

Sql 统计表中特定值的出现次数的步骤,sql,oracle,Sql,Oracle,我有一张如下所示的表格 Col1 Col2 Col3 * $ * $ * * # * $ % * * * * $ * @ $ 我需要一个sql查询来计算表中的星号(*) 一个选项是按照以下方式编写查询 select ((select count(*) from star_table where col1='*') +

我有一张如下所示的表格

Col1    Col2    Col3
*         $       *
$         *       *
#         *       $
%         *       *
*         *       $
*         @       $
我需要一个sql查询来计算表中的星号(*)

一个选项是按照以下方式编写查询

select ((select count(*) from star_table where col1='*') + 
(select count(*) from star_table where col2='*') +
(select count(*) from star_table where col3='*')) as count from dual.
我想知道是否有其他方法可以编写查询以获得相同的结果

请尝试:

SELECT SUM(
    (CASE WHEN Col1='*' THEN 1 ELSE 0 END)+
    (CASE WHEN Col2='*' THEN 1 ELSE 0 END)+
    (CASE WHEN Col3='*' THEN 1 ELSE 0 END)) 
FROM TableName
更新:如果列中包含的字符串长度不超过个字符,则可以:

select sum(3 - length(replace(col1||col2||col3,'*')))
from star_table; 
你要的:)

这个怎么样

对于SQL Server,这里是:

select sum(patindex('*',col1)) +
sum(patindex('*',col2)) +
sum(patindex('*',col3))
from stars
;

结果:

| TOTALSTARS |
--------------
|         10 |
| TOTALSTARS |
--------------
|         10 |
在Florin指出之前,我将您的sql开发人员误认为是sql server,下面是Oracle的版本:

结果:

| TOTALSTARS |
--------------
|         10 |
| TOTALSTARS |
--------------
|         10 |
这个怎么样

    select sum(decode(col1,'*',1,0)+decode(col2,'*',1,0)+decode(col3,'*',1,0)) 
    from tab;

看看这个,结果似乎是一样的:)你能告诉我预期的答案吗?再说一遍,这是Oracle而不是MySql。在oracle SQL中,您没有布尔值,如何添加布尔值哦,是的。。哦,天哪。对不起@Florin然后你明白了,伙计:)我在做sql开发人员,我得到一个错误,执行这个查询时出现了“缺少正确的偏执”,这个查询看起来简单又好,但它在sql开发人员中抛出了错误。。需要帮助这比你的快。一次扫描而不是三次。不过,我会考虑一个较小的版本。
    select sum(decode(col1,'*',1,0)+decode(col2,'*',1,0)+decode(col3,'*',1,0)) 
    from tab;