SELECT SUM(man+woman) AS over65,
a.cod,
a.city,
b.cod2
FROM a LEFT JOIN
b ON b.cod2 = a.cod
GROUP BY cod
-
table a
cod city
28001 rome
28001 rome
28002 milan
28002 milan
table b
cod2 age man woman
28001 65 156 220
28001 66 250 280
28001 67 350 483
28002 65 556 524
28002 66 650 683
28002 67 450 342
result Is:
cod city over65
28001 rome 3478
28002 milan 6410
instead Of :
cod city over65
28001 rome 1739
28802 milan 3205
我该怎么做? 感谢
答案 0 :(得分:1)
使用子查询来删除表a
中的重复项。
SELECT SUM(man+woman) AS over65,
a.cod,
a.city,
b.cod2
FROM (SELECT DISTINCT cod, city
FROM a) AS a
LEFT JOIN
b ON b.cod2 = a.cod
GROUP BY a.cod
我也想知道为什么表a
首先有重复的表。如果city
对于给定的cod
始终相同,则数据未正确规范化。