sql iif语句连接表问题

时间:2011-11-15 05:34:25

标签: sql sql-server ms-access

我想产生结果:

table name: HWData
policy number:        number of residents:   factor:
100                     2                      1
101                     4                      1.25
102                     7                      2
103                     99                     2
104                     1                      0.85

使用规则:

table name: Tier_Occupancy
number of residents:   factor:
1                       0.85
2                       1  
3                       1.10
4                       1.25
5                       1.5
6 or above              2.0

这是我到目前为止所做的:

SELECT 
HWData.[Policy Number], 
iif( HWData.[Number of Residents] = 1, Tier_Occupancy.Factor,1 ), 
iif( HWData.[Number of Residents] = 2, Tier_Occupancy.Factor, 1), 
iif( HWData.[Number of Residents] = 3, Tier_Occupancy.Factor, 1), 
iif( HWData.[Number of Residents] = 4, Tier_Occupancy.Factor, 1), 
iif( HWData.[Number of Residents] = 5, Tier_Occupancy.Factor, 1), 
iif( HWData.[Number of Residents] >= 6, Tier_Occupancy.Factor, 1)

FROM HWData 
INNER JOIN Tier_Occupancy ON HWData.[Number of Residents]=Tier_Occupancy.[Number of Residents]

ORDER BY HWData.[Policy Number];

我的问题是它确实显示了结果,但它显示了政策号100的1 1 1 1 1 1 它显示了政策号101的1 1 1 1.25 1 1但我不希望这样:我只想为政策号100显示1,为政策号101显示1.25。

我使用的是2007 Microsoft Access的SQL。

2 个答案:

答案 0 :(得分:2)

替换此

iif( HWData.[Number of Residents] = 1, Tier_Occupancy.Factor,1 ), 
iif( HWData.[Number of Residents] = 2, Tier_Occupancy.Factor, 1), 
iif( HWData.[Number of Residents] = 3, Tier_Occupancy.Factor, 1), 
iif( HWData.[Number of Residents] = 4, Tier_Occupancy.Factor, 1), 
iif( HWData.[Number of Residents] = 5, Tier_Occupancy.Factor, 1), 
iif( HWData.[Number of Residents] >= 6, Tier_Occupancy.Factor, 1)

用这个

Tier_Occupancy.Factor

需要修复联接。这是您需要使用IIF的地方。

ON iif(HWData.[Number of Residents]>5,6,HWData.[Number of Residents]) = Tier_Occupancy.[Number of Residents]

并从Tier_Occupancy表的最后一个“居民人数”条目中的最后一个条目中删除“或以上”。那应该是一个数字列。

此外,不要忘记在结果中按照您的意愿选择居民数量列。

答案 1 :(得分:1)

SELECT 
HWData.[Policy Number], 
   (select top 1 Tier_Occupancy.Factor from Tier_Occupancy 
    where Tier_Occupancy.[Number of Residents] <= HWData.[Number of Residents]
   order by Tier_Occupancy.[Number of Residents] desc) as factor
FROM HWData 

ORDER BY HWData.[Policy Number];