我正在尝试将表连接到映射表。映射表中包含地理数据,其想法是首先查看最详细的信息,例如Postalcode和mapp,如果没有提供邮政编码,它将查看该区域:
ID Region Country Description Zone County City Postal_Code
9324 Australasia Australia Tasmania 70 Western Shore 7000
9325 Australasia Australia Tasmania 70 Western Shore 7004
9326 Australasia Australia Tasmania 70 Western Shore 7005
9327 Australasia Australia Tasmania 70 Western Shore 7007
9328 Australasia Australia Tasmania 70 Western Shore 7008
9329 Australasia Australia Tasmania 70 Western Shore 7009
9330 Australasia Australia Tasmania 70 Western Shore 7010
9331 Australasia Australia Tasmania 70 Western Shore 7011
9332 Australasia Australia Tasmania 70 Western Shore 7012
9333 Australasia Australia Tasmania 70 Eastern Shore 7015
9334 Australasia Australia Tasmania 70 Eastern Shore 7016
9335 Australasia Australia Tasmania 70 Western Shore 7017
9336 Australasia Australia Tasmania 70 Eastern Shore 7018
9337 Australasia Australia Tasmania 70 Eastern Shore 7019
9338 Australasia Australia Tasmania 70 Eastern Shore 7020
9339 Australasia Australia Tasmania 70 Eastern Shore 7021
9340 Australasia Australia Tasmania 70 Eastern Shore 7022
9341 Australasia Australia Tasmania 70 Eastern Shore 7023
9342 Australasia Australia Tasmania 70 Eastern Shore 7024
9343 Australasia Australia Tasmania 70 Sorell 7025
9344 Australasia Australia Tasmania 70 Sorell 7026
9345 Australasia Australia Tasmania 70 Sorell 7027
9346 Australasia Australia Tasmania 70 Western Shore 7030
9347 Australasia Australia Tasmania 70 Kingston 7050
9348 Australasia Australia Tasmania 70 Kingston 7052
9349 Australasia Australia Tasmania 70 Kingston 7053
9350 Australasia Australia Tasmania 70 Kingston 7054
9351 Australasia Australia Tasmania 70 Kingston 7055
我们的想法是,所有内容都会返回到区域和描述,但加入依赖于提供的数据,因此我尝试格式化的数据是:
COUNTRY STATE Zone ZIP TIV
Australia NULL 70 NULL 1000000
Australia NULL 70 NULL 1000000
Australia NULL 70 NULL 1000000
Australia NULL 70 NULL 1000000
Australia NULL NULL 7023 100000
所以答案如下:
COUNTRY Zone NAME Value
Australia 70 Tasmania 4000000
但是我的代码是:
SELECT GR.COUNTRY,
GR.ZONE,
GR.Zone_Desc AS NAME,
sum(TA.TIV)
FROM [dbo].[Tmp_Format] TA
INNER JOIN [dbo].[GeoRes_Mapping] GR ON TA.COUNTRY = GR.Country AND TA.Zone = GR.Zone
WHERE TA.COUNTRY = 'Australia'
GROUP BY GR.COUNTRY,
GR.ZONE,
GR.Zone_Desc,
TA.TIV
我实际得到的是:
COUNTRY ZONE NAME Value
Australia 70 Tasmania 112000000
它似乎是将4100000乘以我的映射表中的28个不同区域?抱怨道歉这么久,但我真的很难挣扎
答案 0 :(得分:1)
它不是乘以不同的区域,而是乘以邮政编码。每个区域有多个行。也许这会解决你的问题:
SELECT GR.COUNTRY, GR.ZONE, GR.Zone_Desc AS NAME, sum(TA.TIV)
FROM [dbo].[Tmp_Format] TA INNER JOIN
(select distinct country, zone, zone_desc
from [dbo].[GeoRes_Mapping]
) GR
ON TA.COUNTRY = GR.Country AND TA.Zone = GR.Zone
WHERE TA.COUNTRY = 'Australia'
GROUP BY GR.COUNTRY, GR.ZONE, GR.Zone_Desc;
此外,TIV
不应该出现在group by
。