0

我有一个 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 

有人可以解释我的查询哪里错了吗?

4

2 回答 2

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
于 2013-02-05T12:47:29.783 回答
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
于 2013-02-05T12:45:44.627 回答