MS Access 2003:检查数据是否在另一个表的范围内

时间:2011-01-25 17:05:56

标签: sql ms-access

我有两张桌子,表A有小时,表B有等级,最低小时要求

我要做的是根据每条记录的小时数将TableB.Grade分配给TableA。

示例:

表A

Name        Hours       
Person A     205
Person B     105
Person C     400

表B

Grade       HoursRequired
1              0
2              100
3              200
4              300

我的预期报告

Name      Hours     Grade
Person A    105     2
Person B    205     3
Person C    400     4

任何有关SQL编码或表重组的建议都将受到赞赏。

2 个答案:

答案 0 :(得分:1)

您可以使用子查询:

select  A.Name
,       A.Hours
,       (
        select  top 1 grade 
        from    TableB B 
        where   B.HoursRequired <= A.Hours 
        order by 
                B.HoursRequired DESC
        ) as Grade
from    TableA A

答案 1 :(得分:0)

我喜欢@Andomar的建议。但是,如果子查询混淆了您,您可以像这样修改TableB:

Grade low_end   high_end
1           0         99
2         100        199
3         200        299
4         300 2147483647

然后使用此查询:

SELECT a.person_name, a.hours, b.Grade
FROM TableA AS a, TableB AS b
WHERE (((a.hours) Between [b].[low_end] And [b].[high_end]))
ORDER BY a.person_name;

名称是保留字,因此我将您的名称字段重命名为person_name。

相关问题