简体   繁体   English

MySQL将不同值的计数选择到单独的列中

[英]MySQL select count of distinct values into seperate columns

I want to get the count of rows for each distinct value in column A grouped by column B like this: 我想获得按列B分组的A列中每个不同值的行数,如下所示:

------------------------------------------------------
| B | AValue1 | AValue2 | Avalue3 | AValue4 | ......  |
------------------------------------------------------
|B1 |    x    |    x    |    x    |    x    |    x    |
|B2 |    x    |    x    |    x    |    x    |    x    |
|...|    x    |    x    |    x    |    x    |    x    |
-------------------------------------------------------

x being the different counts. x是不同的计数。 Right now i am getting basically the same data using "Group By(A,B)" but it is in the form: 现在,我正在使用“ Group By(A,B)”获得基本相同的数据,但其形式为:

----------------------------------------------
| A         |    B     |   Count             |
----------------------------------------------    
| AValue1   | BValue1  |     x               |
| ...       | ....     |     x               |
----------------------------------------------

after which i have to transform the Data in PHP or on the client in Javascript. 之后,我必须在PHP或Javascript的客户端上转换数据。 The only way i could come up with to get the first table would be to do a subquery select for each of the values in A, but that defeats the purpose of it being a simpler and cleaner solution. 我想得到第一个表的唯一方法是对A中的每个值进行子查询选择,但这违背了它成为更简单,更干净的解决方案的目的。 Is there an easy way to achieve this in SQL or is transformation of the Group By table the best approach? 有没有一种简单的方法可以在SQL中实现此目标,或者对Group By表进行转换是最佳方法? Thanks in Advance 提前致谢

@GolezTrol's comment pointed me in the right direction. @GolezTrol的评论为我指明了正确的方向。 MySQL sadly doesnt have PivotTables, but i managed to solve it using the following group concat statement: 可悲的是,MySQL没有PivotTables,但是我设法使用以下group concat语句解决了它:

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'SUM(IF(B = ''',
      B,
      ''', 1, 0)) AS `',
      B,
      '`'
    )
  ) INTO @sql
FROM table
SET @sql = CONCAT('SELECT A, ', @sql, ' FROM table GROUP BY A');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

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

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