我有一张如下所示的表格
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.
我想知道是否有另一种编写查询的方法来获得相同的结果。
答案 0 :(得分:2)
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 star_table;
更新:如果您的列包含字符长度字符串,您可以:
select sum(3 - length(replace(col1||col2||col3,'*')))
from star_table;
你问过这个问题:)
答案 1 :(得分:1)
请尝试:
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
答案 2 :(得分:0)
这个怎么样?
select sum(col1='*') + sum(col2='*') + sum(col3='*')
from yourtable
对于SQL Server,这里是:
select sum(patindex('*',col1)) +
sum(patindex('*',col2)) +
sum(patindex('*',col3))
from stars
;
结果:
| TOTALSTARS |
--------------
| 10 |
我把你的sql开发人员误认为sql server直到Florin指出,这里是 Oracle 版本:
select sum(instr('*',col1)) +
sum(instr('*',col2)) +
sum(instr('*',col3)) as TotalStars
from stars
;
结果:
| TOTALSTARS |
--------------
| 10 |
答案 3 :(得分:0)
这个怎么样?
select sum(decode(col1,'*',1,0)+decode(col2,'*',1,0)+decode(col3,'*',1,0))
from tab;