简体   繁体   English

将多行的选定列合并为一行

[英]Combine selected columns of multiple rows into one row

I want to count the number of male & female user of each religion of each age to obtain a resulting table like the third table below. 我想计算出每个年龄段每种宗教的男女使用者的数量,以得出结果表,如下面的第三表。

tbl_user: tbl_user:

id  name      dob           gender religion
1   raj       1999-12-21       m      1 
7   raju      1998-10-10       m      2 
8   rajan     2000-11-23       m      3 
11  neetu     1992-12-06       f      1 
12  sita      1993-06-16       f      2 
13  rita      1992-06-08       f      3 
14  jenny     1993-05-10       f      2 
15  manju     1993-12-16       f      1 
16  aanju     1993-03-05       f      3 
17  raja      1995-04-06       m      1 
18  rajendra  1995-07-03       m      2 
19  rajesh    1991-05-02       m      3

tbl_religion: tbl_religion:

id  name 
1   Christian 
2   Hindu 
3   Islam

Now I want to count the number of male & female user of each religion of each age to obtain a resulting table like the one below. 现在,我想计算每个年龄段每种宗教的男性和女性使用者数量,以得出如下表。 The user can be of any age or or born on any year: 用户可以是任何年龄或任何年龄的人:

Age Christian Male Christian Female Hindu Male Hindu Female Islam Male Islam Female 
14        0             0           0         0             1            0 
15        1             0           0         0             0            0 
16        0             0           1         0             0            0 
20        1             0           1         0             0            0 
21        0             1           0         0             0            0 
22        0             1           0         2             0            1 
23        0             0           0         0             1            1 
24        0             0           0         0             0            0 

You can use the timestampdiff function to calculate the age, and use conditional aggregation to count the number in each category like below. 您可以使用timestampdiff函数来计算年龄,并使用条件聚合来计算每个类别中的数字,如下所示。

select 
    timestampdiff(year, dob, now()) age 
    , sum(gender = 'm' and r.name = 'Christian') Christian_Male
    , sum(gender = 'f' and r.name = 'Christian') Christian_Female
    , sum(gender = 'm' and r.name = 'Hindu') Hindu_Male
    , sum(gender = 'f' and r.name = 'Hindu') Hindu_Female
    , sum(gender = 'm' and r.name = 'Islam') Islam_Male
    , sum(gender = 'f' and r.name = 'Islam') Islam_Female
from tbl_user u
join tbl_religion r on u.religion = r.id 
group by timestampdiff(year, dob, now());

Sample SQL Fiddle 示例SQL提琴

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

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