简体   繁体   English

MYSQL 计算一行的不同值与另一行的不同值

[英]MYSQL count different values of a row with distinct value of another row

Using the below query i'm able to get the count of male and female of each municipality but the problem is municipalities come in duplicate entries, I want all same municipalities to come in one row and all their male and females be counted all together.使用下面的查询,我可以获得每个市镇的男性和女性人数,但问题是市镇有重复的条目,我希望所有相同的市镇排成一排,并将他们所有的男性和女性一起计算。 Someone please help me:(有人请帮助我:(

I need the data of Gender and Training Location columns of the table2 and it is inner join with table1 because for each record of table1 I have many records in table2.我需要 table2 的 Gender 和 Training Location 列的数据,它是与 table1 的内连接,因为对于 table1 的每条记录,我在 table2 中有很多记录。

Please refer to the below picture of what i currently get through this query请参考下图,了解我目前通过此查询获得的信息

Select 
  (Select count(*) from table2 where gender='Male' and table1.ID=table2.ID) AS Male, 
  (Select count(*) from table2 where gender='Female' and table1.ID=table2.ID) AS Female,  
  Training_Location 
from table2 
INNER JOIN table1 ON table1.id = table2.ID 
WHERE table1.Training_Start_Date BETWEEN '$StartDate' and '$EndDate' 
group by table1.ID

截屏

I think you want to remove the JOIN in the outer query:我认为您想删除外部查询中的JOIN

select t1.id, t1.Training_Location 
       (Select count(*) from table2 t2 where t2.gender='Male' and t1.I D= t2.ID) AS Male, 
       (Select count(*) from tbl_ind1_sub tis where tis.gender ='Female' and t1.ID = tis.ID) AS Female,  
from table1 t1 ON table1.id = table2.ID 
where t1.Training_Start_Date between ? and ?;

It seems really strange to me that males and females would be in separate tables.对我来说,男性和女性会在不同的桌子上,这似乎真的很奇怪。 But that is how your question is structured.但这就是您的问题的结构。

Note that no group by is needed in the outer query, assuming the id is unique (a reasonable assumption).请注意,外部查询中不需要group by ,假设id是唯一的(一个合理的假设)。

Also, do not munge queries with constants.此外,不要使用常量进行查询。 Pass them into the query as parameters.将它们作为参数传递到查询中。

If you decide that the tables in the subquery are the same table, ask a new question.如果您确定子查询中的表是同一个表,请提出一个问题。 This question clearly has them as separate tables.这个问题显然将它们作为单独的表格。

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

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