MYSQL内连接带有count子查询

时间:2013-02-05 12:39:38

标签: mysql sql join

我有一个Mysql查询,它从2个表中选择一些具有内连接的列。它应该从一个表列中计算“Y”值,并使用Group By来计算此计数。

这是我的疑问:

SELECT (SELECT Count(tblinterview.Contacted) FROM tblinterview WHERE tblinterview.Contacted = "Y") 
as Contact_Y , tbldata.RegionID, tbldata.BranchCode, tbldata.BranchDesc, tbldata.CampaignID,      tblinterview.EndTime      
FROM tbldata INNER JOIN tblinterview 
WHERE tblinterview.DataID = tbldata.DataId 
AND tblinterview.Complete = "Y"
GROUP BY tbldata.BranchCode, tbldata.RegionID, tblinterview.EndTime

我的结果集是: 其中所有Contact_Y是所有记录的总数而不是分组计数。

Contact_Y      RegionID        BranchCode           BranchDesc     CampaignID   EndTime
1407            1           9725            Dada Motors        31           2012-01-26 12:51:12
1407            1           9725            Dada Motors        31           2012-01-31 10:25:18
1407            1           9725            Dada Motors        31           2012-02-01 11:30:37
1407            1           9725            Dada Motors        31           2012-02-01 14:48:57
1407            3           9732            Ballito Autohaus   37       2012-01-16 15:04:12
1407            3           9732            Ballito Autohaus   46           2012-01-18 11:59:53
1407            3           9732            Ballito Autohaus   31           2012-01-20 14:26:12
1407            3           9732            Ballito Autohaus   31           2012-01-20 16:05:48 

有人可以解释我的查询错误吗?

2 个答案:

答案 0 :(得分:4)

试一试

SELECT   (SELECT Count(s.Contacted) 
        FROM tblinterview s
        WHERE s.Contacted = "Y" AND 
        tbldata .DataID = s.DataID) as Contact_Y , 
        tbldata.RegionID, 
        tbldata.BranchCode, 
        tbldata.BranchDesc, 
        tbldata.CampaignID,      
        tblinterview.EndTime      
FROM    tbldata 
        INNER JOIN tblinterview  ON tblinterview.DataID = tbldata.DataId 
WHERE   tblinterview.Complete = "Y"
GROUP BY tbldata.BranchCode, tbldata.RegionID, tblinterview.EndTime

答案 1 :(得分:1)

SELECT
  Count(tblinterview.Contacted) as Contact_Y,
  tbldata.RegionID,
  tbldata.BranchCode,
  tbldata.BranchDesc,
  tbldata.CampaignID,
  tblinterview.EndTime
FROM
  tbldata INNER JOIN tblinterview
  ON (tblinterview.DataID = tbldata.DataId
      AND tblinterview.Contacted = "Y")
GROUP BY
  tbldata.BranchCode,
  tbldata.RegionID,tblinterview.EndTime