2

i have one table with a single column having three values a,b and c. Current snapshot of the table is

Table name:- tblTest

Values

tblColumn
a
a
a
b
b
b
b
c
c

i need to get the output exactly as

A B C
3 4 2

3 Answers 3

4
select sum(tblColumn = 'a') as A,
    sum(tblColumn = 'b') as B,
    sum(tblColumn = 'b') as C
from tblTest

SQL Fiddle Example

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

Comments

3
SELECT  SUM(CASE WHEN colName = 'a' THEN 1 ELSE 0 END) as A,
        SUM(CASE WHEN colName = 'b' THEN 1 ELSE 0 END) as B,
        SUM(CASE WHEN colName = 'c' THEN 1 ELSE 0 END) as C
FROM tableName

another technique is by using PreparedStatement, this is very good if you have multiple unknown number group of values, eg, a,b,c,d,e,f,g,h,...

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'SUM(IF(tblColumn = ''',
      tblColumn,
      ''', 1, 0)) AS ',
      tblColumn 
    )
  ) INTO @sql
FROM
  Table1;
SET @sql = CONCAT('SELECT ', @sql, ' FROM Table1');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SQLFiddle Demo

3 Comments

Note the values are lowercase. When comparing "case insensitive" the results will be the same either way. But when comparing "case sensitive" you have to use lowercase values too.
@MihaiStancu yep, anyway i just added prepared statement.
2

Try this

select tblColumn, Count(*) from tblTest group by tblColumn

2 Comments

The result set won't be structured as requested.
Agree, RedFilter... we can do without Distinct().. :) Changed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.