按单列对数据进行分组,但希望将它们显示为列

时间:2018-03-15 03:05:59

标签: mysql

我正在处理我的小项目,其中我有一个情况,我们需要显示如下报告:

gender    gender_count    rejected     selected  
Male      230             50           180  
Female    150             20           130  

上述报告中的所有值(不包括性别列)都是从表中计算的。

表结构如下:

 user_id     gender    status  
 1           male      selected  
 2           male      selected  
 3           female    rejected  
 4           female    selected  
 5           male      rejected  

我无法为这种报告编写查询。我正在使用group by计算性别。但我如何按地位统计性别,然后将其作为列。

请帮我解决这个问题。提前致谢。

4 个答案:

答案 0 :(得分:1)

SELECT
GENDER, COUNT(*) GENDER_COUNT, 
SUM(IF(STATUS='REJECTED',1,0)) REJECTED,
SUM(IF(STATUS='SELECTED',1,0)) SELECTED
FROM 
TABLE
GROUP BY GENDER

您需要使用CASE代替IF

的其他数据库

(我不是MySQL专家,但这应该以正确的方式指出你)

答案 1 :(得分:0)

试试这个:

SELECT gender, COUNT(*) gender_count, SUM(status='rejected') rejected, 
       SUM(status='selected') selected 
FROM yourTable
GROUP BY gender;

答案 2 :(得分:0)

我已经通过SQLfiddle检查了下面提供的链接,你可以查看它... http://sqlfiddle.com/#!9/822019/3

 CREATE TABLE table1 (
        user_id int,
        gender varchar(255),
        status varchar(255)

    );

    INSERT INTO table1 VALUES (1,"male","selected"),
    (2,"male","selected"),
    (3,"female","rejected"),
    (4,"female","selected"),
    (5,"male","rejected");

SELECT
gender, COUNT(*) GENDER_COUNT, 
SUM(IF(STATUS='REJECTED',1,0)) REJECTED,
SUM(IF(STATUS='SELECTED',1,0)) SELECTED
FROM 
table1
GROUP BY gender

答案 3 :(得分:0)

适合您的情况

 mysql> select   * from genderlist;
    +---------+--------+--------+
    | user_id | gender | status |
    +---------+--------+--------+
    |       1 | male   | select |
    |       2 | female | select |
    |       3 | female | reject |
    |       4 | female | reject |
    |       5 | male   | reject |
    |       6 | male   | select |
    +---------+--------+--------+

尝试以下查询

  

选择性别,计算(*)作为gendercount,sum(status ='选择')选择',sum(status ='拒绝')as按性别拒绝性别列表组;

输出

mysql> SELECT gender,count(*) as gendercount,sum(status='select') as 'selected',sum(status='reject') as reject from genderlist group by gender;
+--------+-------------+----------+--------+
| gender | gendercount | selected | reject |
+--------+-------------+----------+--------+
| female |           3 |        1 |      2 |
| male   |           3 |        2 |      1 |
+--------+-------------+----------+--------+