mysql从where子句获取总值和总数

时间:2017-05-16 15:58:50

标签: mysql

我正在尝试编写一个mysql查询,该查询将返回列中值的总数以及基于同一列中where子句的值总数。

我有一张这样的表:

+------------------------+-------+
| color                  | code  |
+------------------------+-------+
| red                    |   200 |
| red                    |   202 |
| blue                   |   105 |
| yellow                 |   136 |
| green                  |   561 |
| red                    |   198 |
| blue                   |   414 |
| green                  |   11  |
| yellow                 |   600 |
| green                  |   155 |
| red                    |   865 |
| blue                   |   601 |
| green                  |   311 |
+------------------------+-------+

如果我运行此查询:

select 
    color, 
    count(*) as count 
from colors 
where code > 0 && 
    code <= 500 
group by color 
order by count(*) desc;

我得到的结果非常好,因为它几乎是我想要的:

+------------------------+-------+
| color                  | count |
+------------------------+-------+
| red                    |     3 |
| green                  |     3 |
| blue                   |     2 |
| yellow                 |     1 |
+------------------------+-------+

我还需要返回的是列中值的总数,因此结果表将如下所示。

+------------------------+--------------+-------+
| color                  | total        | count |
+------------------------+--------------+-------+
| red                    |            4 |     3 |
| green                  |            4 |     3 |
| blue                   |            3 |     2 |
| yellow                 |            2 |     1 |
+------------------------+--------------+-------+

因此总数是颜色列中每个值的数量,count是与where子句匹配的总量。

谢谢:)

这是SQLFiddle的链接。

http://sqlfiddle.com/#!9/777f93/2

5 个答案:

答案 0 :(得分:2)

您需要使用条件聚合来处理计数并让引擎处理总数。

library(magrittr)
df %<>% mutate(type=mapply(.$x,.$y, FUN=function(x,y) if ((x=='A')  && (y==1))  "type1"   else "type2"))

答案 1 :(得分:2)

您可以使用条件聚合:

select color,
    count(*) as Total,
    sum(code > 0 and code <= 500) as count_0_to_500
from colors
group by color
order by count_0_to_500 desc

它使用了以下事实:true计算结果为1,而在MySQL中,false计算结果为0。

这基本上就是xQbert在没有案例表达的情况下回答的问题。

答案 2 :(得分:1)

您可以使用其他查询$permissions = ['email', 'user_birthday']; $loginUrl = $helper->getLoginUrl('http://{your-website}/login-callback.php', $permissions); 查询,例如:

JOIN

答案 3 :(得分:1)

您使用case语句来仅计算符合条件的项目。像这样:

Select 
color
, count(*) as total
, SUM(CASE WHEN code > 0 && code <= 500 THEN 1 ELSE 0 END ) as Count
group by color order by count(*) desc;

答案 4 :(得分:1)

您可以使用联接查询和表别名

来执行此操作
    select t1.color,t1.total,t2.count 
FROM 
(select color, count(*) as total from colors group by color) t1,
(select color, count(*) as `count` from colors where `code` > 0 && `code` <= 500 group by color) t2
WHERE
t1.color=t2.color order by `count` desc;

这是SQLFiddle的链接。

http://sqlfiddle.com/#!9/777f93/2