Mysql查询:count列

时间:2017-02-22 16:51:30

标签: mysql

大家好我有技术问题,我有一张包含这样记录的表:

DATE        SIP DURATION  TYPE
2017-02-22  670    9      NO ANSWER
2017-02-22  670    9      ANSWER
2017-02-22  670    9      ANSWER
2017-02-22  671    9      NO ANSWER

我希望得到这样的结果:

SIP   DURATION  NOANSWER  ANSWER
670     18         1        2
671     9          1        0

我会像这样进行查询:

select 
DISTINCT(SIP),
(select count(*) FROM table where TYPE="ANSWERED")
(select count(*) FROM table where TYPE="NO ANSWERED")
from table

但结果计算表上的所有记录,最好使用group by?

抱歉,我是菜鸟:( 谢谢你的时间 马可

1 个答案:

答案 0 :(得分:1)

在这种情况下,使用条件GROUP BYSUM COUNT更容易,如下例所示:

SELECT 
    SIP,
    SUM(CASE TYPE WHEN 'ANSWER' THEN DURATION ELSE 0 END) AS DURATION,
    COUNT(CASE WHEN TYPE = 'NO ANSWER' THEN 1 ELSE NULL END) AS NOANSWER,
    COUNT(CASE WHEN TYPE = 'ANSWER' THEN 1 ELSE NULL END) AS ANSWER
FROM table_name
GROUP BY SIP
  

演示: http://sqlfiddle.com/#!9/b1142/2/0