添加Mysql并将它们添加为新列

时间:2012-04-18 10:10:59

标签: php mysql count case

我想获取2列计数并将其总计作为新列。 我怎么能这样做?

我写了这个查询,但是这总是返回错误。

SELECT count(case when `status`='1' then 1 else 0 end) AS HOT,
count(case when `status`='5' then 1 end) 
AS Special_Case,count(case when 1=1 then 1 end) AS TOTAL 
FROM `tbl_customer_conversation` group by 
date(`dt_added`),user_id

1 个答案:

答案 0 :(得分:2)

COUNT只会给匹配记录的次数,在您的查询中始终会返回1.因为值可以是10。因此count(1)也是1而count(0)也是1

AS,您希望HOT个案例的总数和SPECIAL_CASE必须使用SUM。

SELECT 
    SUM(case when `status`='1' then 1 else 0 end) AS HOT,
    SUM(case when `status`='5' then 1 end) AS Special_Case,
    SUM(case when `status` = '1' or `status` = '5' then 1 end) AS TOTAL 
FROM `tbl_customer_conversation` 
group by date(`dt_added`),user_id