对于不同条件,我在单列上需要3种不同的计数。
表格结构:
interview-
id-int(10)
c_id-int(10)
experience-varchar2(100)
经验有3个不同的价值 - 1)正 2)负 3)中性
对于c_id = 10的条件,我需要3个不同的“count_positive”,“count_negative”和“count_neutral”计数。
我知道它可以通过3个不同的查询获得。我可以通过单个查询获得3个计数吗?
答案 0 :(得分: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
答案 1 :(得分: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'
答案 2 :(得分:1)
这是Adam Wenger的修改版本答案:
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
答案 3 :(得分:1)
我认为这很好用:
select 'count of ' + experience,
count(experience)
from interview
where c_id=10
group by experience
答案 4 :(得分:1)
我在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;