简体   繁体   English

来自同一列的SQL计数值

[英]SQL count values from same column

Hi I have mysql table named content where i have a column "status" which have 3 values, converted , negotiating and received . 嗨,我有一个名为content的mysql表,其中我有一个“状态”列,该列具有3个值,经过convertednegotiatingreceived now i want to count how many have status received, negotiating, and converted for developing a chart. 现在,我想统计有多少人获得了地位,正在就发展图表进行谈判和转换。

here is what i used: 这是我用的:

SELECT status,
SUM(CASE WHEN status = 'converted' = 1 THEN 1 ELSE 0 END) AS converted,
SUM(CASE WHEN status = 'negotiating' = 1 THEN 1 ELSE 0 END) AS negotiating,
SUM(CASE WHEN status = 'Received NA' = 1 THEN 1 ELSE 0 END) AS ReceivedNA
FROM content GROUP BY status; 

It shows me the result but in a way that i can not use it. 它向我显示了结果,但以某种方式我无法使用它。

to feed my chart i used this: 喂我的图表,我用这个:

$data = array(
        array('converted', $converted),
        array('negotiating', $negotiating),
        array('received', $received)
    );

So i guess some thing like this table will solve my problem: 所以我想像这样的表可以解决我的问题:

 status                        result
---------------------------  -------- 
converted                        1
negotiating                      5
received                         4

So can anyone suggest how can modify my sql to get the expected result? 因此,有人可以建议如何修改我的sql以获得预期的结果吗?

thanks again 再次感谢

Use GROUP By . 使用GROUP By Try this - 尝试这个 -

SELECT status, count(status) result FROM content GROUP BY status 

To get the distinct count use GROUP BY. 要获得非重复计数,请使用GROUP BY。

select status,count(1) as result from content GROUP BY status;

Instead of using sum, count is always a better and easier way 而不是使用总和,计数始终是更好,更轻松的方法

EDIT-to answer the comment 编辑-回答评论

The parameter to the COUNT function is an expression that is to be evaluated for each row. COUNT函数的参数是要为每一行求值的表达式。 The COUNT function returns the number of rows for which the expression evaluates to a non-null value. COUNT函数返回表达式计算结果为非空值的行数。 ( * is a special expression that is not evaluated, it simply returns the number of rows.) (*是一个不计算的特殊表达式,它仅返回行数。)

There are two additional modifiers for the expression: ALL and DISTINCT. 该表达式还有两个附加修饰符:ALL和DISTINCT。 These determine whether duplicates are discarded. 这些确定重复项是否被丢弃。 Since ALL is the default, your example is the same as count(ALL 1), which means that duplicates are retained. 由于ALL是默认设置,因此您的示例与count(ALL 1)相同,这意味着将保留重复项。

Since the expression "1" evaluates to non-null for every row, and since you are not removing duplicates, COUNT(1) should always return the same number as COUNT(*). 由于表达式“ 1”的每一行求值为非空,并且由于您没有删除重复项,因此COUNT(1)始终应返回与COUNT(*)相同的数字。

Will this work for you? 这对您有用吗?

SELECT status, count(status) FROM content GROUP BY status; 选择状态,从内容GROUP BY状态开始计数(状态);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM