简体   繁体   English

从一列计算Mysql 5.5中的值并按另一列分组

[英]count values in Mysql 5.5 from one column and group by other column

I want to know number of column1 value group by column2 and total count in mysql 5.5 .我想知道在mysql 5.5 中按 column2 分组的 column1 值的数量和总数。 below example will help to understand my problem:下面的例子将有助于理解我的问题:

-------------------
column1 | column2
-------------------
of      | d1
of      | d1
sf      | d2
sf      | d3
sf      | d3
tf      | d2
tf      | d3
tf      | d1
of      | d1
-------------------

the output will be:输出将是:

------------------------------
column2 | of | sf | tf | total
-------------------------------
d1      | 3  | 0  |  1 | 4
d2      | 0  | 1  |  1 | 2
d3      | 0  | 2  |  1 | 3
------------------------------

I searched but didn't found exact solution for my scenario.我进行了搜索,但没有找到适合我的场景的确切解决方案。 I can do it with RANK but 5.5 will not support RANK function.我可以用 RANK 来做,但 5.5 不支持 RANK 功能。

You can do it with conditional aggregation:您可以使用条件聚合来做到这一点:

select column2,
  sum(column1 = 'of') of,
  sum(column1 = 'sf') sf,
  sum(column1 = 'tf') tf,
  count(*) total
from tablename
group by column2

See the demo .请参阅演示
Results:结果:

| column2 | of  | sf  | tf  | total |
| ------- | --- | --- | --- | ----- |
| d1      | 3   | 0   | 1   | 4     |
| d2      | 0   | 1   | 1   | 2     |
| d3      | 0   | 2   | 1   | 3     |

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

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