此查询提供多行

时间:2017-05-31 14:36:16

标签: sql sql-server

我有多个连接的查询,它给了我重复的记录....这是我的查询

SELECT     tblB.City, tblA.ShortDesc, 
                  SUM(CASE WHEN Code = 'M' THEN 1 ELSE 0 END) AS Male, 
                  SUM(CASE WHEN Code = 'F' THEN 1 ELSE 0 END) As Female

FROM         tblC INNER JOIN
                  tblB ON tblC.ID = tblB.ID INNER JOIN
                  tblE ON tblC.Number = tblE.Number INNER JOIN
                  tblA ON tblE.ServiceID = tblA.ServiceID INNER JOIN
                  tblD ON tblC.IDNumber = tblC.IDNumber
WHERE     (tblA.ServiceID IN (71)) AND (tblC.Date BETWEEN '1/12/2017' AND '2/31/2017')
GROUP BY tblB.City, tblA.ShortDesc, tblD.Code

所以这个查询应该给我看起来像这样的结果......

City         Male       Female
LA           17         21
SF           23         7

但我得到的就是这个......

City         Male       Female
LA           17         0
LA           0          21
SF           23         0
SF           0          7

任何人都知道为什么会这样?

1 个答案:

答案 0 :(得分:4)

您应该从查询中删除GROUP BY tblD.Code

SELECT 
 tblB.City, 
 tblA.ShortDesc, 
 SUM(CASE WHEN Code = 'M' THEN 1 ELSE 0 END) AS Male, 
 SUM(CASE WHEN Code = 'F' THEN 1 ELSE 0 END) As Female
FROM tblC 
INNER JOIN tblB 
 ON tblC.ID = tblB.ID 
INNER JOIN tblE 
 ON tblC.ReferralNumber = tblE.ReferralNumber 
INNER JOIN tblA 
 ON tblE.ServiceID = tblA.ServiceID 
INNER JOIN tblD 
 ON tblC.IDNumber = tblMember.IDNumber
WHERE (tblA.ServiceID IN (71)) 
 AND (tblC.Date BETWEEN '2017-01-12' AND '2017-02-28')  -- there is no Feb 31
GROUP BY tblB.City, tblA.ShortDesc

由于您在条件聚合中使用该列,因此您无需按其进行分组。该列的值很可能导致多行。