0

How can I count total no. of $ signs present in a table? Simple select query will not work in this case. How should I edit my select query to count string occurrences across multiple columns in a table.

c1 | c2 | c3 | c4 | c5|
$  |    |    | $  |   |  
   | $  |  $ | $  |   |   
   |    |    |    |   |
$  |    |    |    |   |  


($ signs are present randomly in the table in any column) I tried to get the count through regex but it always return no. of rows in which $ is present, not the number of $.

3
  • 1
    No regular expressions are needed. Is this about PostgreSQL or MySQL? Commented Jul 3, 2018 at 10:58
  • yes, postgresSQL or mysql queries are welcome. Commented Jul 3, 2018 at 11:00
  • 2
    You are trying to pivot the data. MySQL does not have a pivot function. You will have to use case statement with count. Commented Jul 3, 2018 at 11:02

1 Answer 1

3

You could use case inside count to count occurrence of $ in your columns

select 
  count(case when c1 = '$' then 1 else null end) 
+ count(case when c2 = '$' then 1 else null end)
+ count(case when c3 = '$' then 1 else null end) 
+ count(case when c4 = '$' then 1 else null end) 
+ count(case when c5 = '$' then 1 else null end) cnt
from your_table

Demo Mysql

Demo Postgre

Sign up to request clarification or add additional context in comments.

1 Comment

M khalid Junaid, it worked, thanks! :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.