簡體   English   中英

MYSQL 計算一行的不同值與另一行的不同值

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

使用下面的查詢,我可以獲得每個市鎮的男性和女性人數,但問題是市鎮有重復的條目,我希望所有相同的市鎮排成一排,並將他們所有的男性和女性一起計算。 有人請幫助我:(

我需要 table2 的 Gender 和 Training Location 列的數據,它是與 table1 的內連接,因為對於 table1 的每條記錄,我在 table2 中有很多記錄。

請參考下圖,了解我目前通過此查詢獲得的信息

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

截屏

我認為您想刪除外部查詢中的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 ?;

對我來說,男性和女性會在不同的桌子上,這似乎真的很奇怪。 但這就是您的問題的結構。

請注意,外部查詢中不需要group by ,假設id是唯一的(一個合理的假設)。

此外,不要使用常量進行查詢。 將它們作為參數傳遞到查詢中。

如果您確定子查詢中的表是同一個表,請提出一個問題。 這個問題顯然將它們作為單獨的表格。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM