6

I require 3 different counts on single column for different conditions.

Table structure:

interview-
id-int(10)
c_id-int(10)
experience-varchar2(100)

experience have 3 different values- 1)positive 2)negative 3)neutral

I require 3 different counts of "count_positive", "count_negative" and "count_neutral" for where condition of c_id=10.

I know it can get by 3 different queries. Can I able to get 3 counts by single query?

Somnath Muluk
  • 55,015
  • 38
  • 216
  • 226

5 Answers5

7
SELECT
   SUM(CASE experience
          WHEN 'positive' THEN 1
          ELSE 0
       END) AS CountPositive
   , SUM(CASE experience
            WHEN 'negative' THEN 1
            ELSE 0
         END) AS CountNegative
   , SUM(CASE experience
            WHEN 'neutral' THEN 1
            ELSE 0
         END) AS CountNeutral
FROM Interview
WHERE c_id = 10
Adam Wenger
  • 17,100
  • 6
  • 52
  • 63
1
select 'Positive Count' , count(*)
from interview
where experience = 'positive'
UNION
select 'Negative Count' , count(*)
from interview
where experience = 'negative'
UNION
select 'Neutral' , count(*)
from interview
where experience = 'neutral'
Zohaib
  • 7,026
  • 3
  • 26
  • 35
1

This is the modified version of Adam Wenger answer:

SELECT
   COUNT(CASE experience
          WHEN 'positive' THEN 1
          ELSE NULL
       END) AS CountPositive
   , COUNT(CASE experience
            WHEN 'negative' THEN 1
            ELSE NULL
         END) AS CountNegative
   , COUNT(CASE experience
            WHEN 'neutral' THEN 1
            ELSE NULL
         END) AS CountNeutral
FROM Interview
WHERE c_id = 10
Yaqub Ahmad
  • 27,569
  • 23
  • 102
  • 149
1

I think this works fine:

select 'count of ' + experience, 
       count(experience) 
from interview 
where c_id=10
group by experience
Carlos Jaime C. De Leon
  • 2,476
  • 2
  • 37
  • 53
1

I got solution for active record query in Codeigniter:

$this->db->select('SUM(CASE experience
          WHEN "positive" THEN 1
          ELSE 0
       END) AS CountPositive
   , SUM(CASE experience
            WHEN "negative" THEN 1
            ELSE 0
         END) AS CountNegative
   , SUM(CASE experience
            WHEN "neutral" THEN 1
            ELSE 0
         END) AS CountNeutral');

$this->db->where('c_id',10);
$query=$this->db->get('interview');
$result=$query->result();

$interview_experience=$result[0];
$positive_count=$interview_experience->CountPositive;
$negative_count=$interview_experience->CountNegative;
$neutral_count=$interview_experience->CountNeutral;
Somnath Muluk
  • 55,015
  • 38
  • 216
  • 226