简体   繁体   English

如何计算SQL中唯一列和行的出现次数?

[英]How to count occurrences with unique columns and rows in SQL?

This question is very similar to : https://stackoverflow.com/posts/1503959/edit But I want to take it one step further, and create new columns for each age, with a count for that age. 这个问题非常类似于: https : //stackoverflow.com/posts/1503959/edit但是我想更进一步,为每个年龄创建新的列,并对该年龄进行计数。

I have a table of people: 我有一个人桌:

name  | age
--------
bill  | 25
tom   | 25
tom   | 23
tom   | 23

I want to query for all names, and additional columns that counts how many names are of the same age: 我想查询所有名称,以及要查询多少个相同年龄的名称的其他列:

name  | 23 | 25
----------------
bill  | 0  | 1
tom   | 2  | 1

What's the most efficient way of doing this? 最有效的方法是什么? I fear that a sub-query will be slow, and I'm wondering if there's a better way . 我担心子查询会很慢,我想知道是否有更好的方法 Is there? 在那儿?

In case you have many age values,dynamic pivot is very useful 如果您有很多年龄值,动态枢纽非常有用

SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'max(case when age = ''',
      age,
      ''' then 1 else 0 end) AS ','`',
      age,'`'
    ) ORDER BY age
  ) INTO @sql
FROM
  t;

SET @sql = CONCAT('SELECT name, ', @sql, ' 
                  FROM t 
                   GROUP BY name');

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

FIDDLE 小提琴

Easiest way how to do this in SQL is using GROUP BY . 在SQL中执行此操作的最简单方法是使用GROUP BY

SELECT name, age, COUNT(*) AS occurence FROM table GROUP BY name, age

But you get data in different format. 但是您会获得不同格式的数据。 You need to reformat them in PHP, because SQL doesn't work way you want. 您需要在PHP中重新格式化它们,因为SQL无法按照您想要的方式工作。

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

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