2014-09-03 185 views
0

我不知道如何計算不同的值。使用如果在選擇列mysql count distinct value

我SQLFIDDLE這裏

http://sqlfiddle.com/#!2/6bfb9/3

記錄顯示:

create table team_record (
    id tinyint, 
    project_id int, 
    position varchar(45) 
); 

insert into team_record values 
(1,1, 'Junior1'), 
(2,1, 'Junior1'), 
(3,1, 'Junior2'), 
(4,1, 'Junior3'), 
(5,1, 'Senior1'), 
(6,1, 'Senior1'), 
(8,1, 'Senior2'), 
(9,1, 'Senior2'), 
(10,1,'Senior3'), 
(11,1, 'Senior3'), 
(12,1, 'Senior3') 

我需要計算所有不同的價值,初級和高級柱之間。

爲1

我需要看到導致這樣的事情都相同的值也要算。

PROJECT_ID SENIOR_TOTAL JUNIOR_TOTAL 
1    3    3 

mysql query is this。但這不是查詢以獲得上述結果。

SELECT 
    `team_record`.`project_id`, 
    `position`,  
    SUM(IF(position LIKE 'Senior%', 
     1, 
     0)) AS `Senior_Total`, 
    SUM(IF(position LIKE 'Junior%', 
     1, 
     0)) AS `Junior_Total` 
FROM 
    (`team_record`)   
WHERE 
    project_id = '1'   
GROUP BY `team_record`.`project_id` 

也許你可以幫助我解決上述問題以獲得我需要的結果。

感謝

+0

如果將數字組分分隔到另一列 – Strawberry 2014-09-03 07:12:48

回答

6

我想你想要這樣的:

​​3210

的情況下將返回NULL,如果當爲false時(即ELSE NULL是默認的,我不再贅述),和零點AREN不計入DISTINCT。

此外,不必要的反勾號,括號和限定刪除。

+0

好答案,這將會更簡單(也更快)。歡呼聲... – Wanderer 2014-09-03 07:05:21

+0

正是這樣!完善!! – freddy 2014-09-03 07:06:43