如何使用舍入值加入 SQL

How to use rounded value for join in SQL

我今天刚开始学习 SQL,我从来没有想过它有多么有趣,直到我摆弄它。
我遇到了问题,需要帮助。

我有 2 tables,客户和费率,详情如下

客户

idcustomer = int  
namecustomer = varchar  
rate = decimal(3,0)  

with value as described:  
idcustomer---namecustomer---rate  
1---JOHN DOE---100  
2---MARY JANE---90   
3---CLIVE BAKER---12  
4---DANIEL REYES---47  

评分

rate = decimal(3,0)  
description = varchar(40)  

with value as described:  
rate---description  
10---G Rank  
20---F Rank  
30---E Rank  
40---D Rank  
50---C Rank  
60---B Rank  
70---A Rank  
80---S Rank  
90---SS Rank  
100---SSS Rank  

然后我 运行 在下面查询以舍入 customer.rate 字段中的所有值,然后以速率 table 内部连接它。

SELECT *, round(rate,-1) as roundedrate
FROM customer INNER JOIN rate ON customer.roundedrate = rate.rate

它没有产生这个结果:

idcustomer---namecustomer---rate---roundedrate---description  
1---JOHN DOE---100---100---SSS Rank  
2---MARY JANE---90---90---SS Rank  
3---CLIVE BAKER---12---10---G Rank  
4---DANIEL REYES---47---50---C Rank  

我的代码有什么问题吗?

我建议为此使用相关子查询:

select c.*,
       (select r.description
        from rate r
        where r.rate <= c.rate
        order by r.rate desc
        fetch first 1 row only
       ) as description
from customer c;

注意:fetch first 1 row only是ANSI标准SQL,有些数据库不支持。 MySQL 使用 limit。 SQL 服务器的旧版本使用 select top 1

您的查询应该会产生一个 'ambigious column' 错误,因为您在引用 rate(在 round(rate,-1) 中)时没有指定 table 名称,这两个名称都存在tables.

此外,sql 查询的 where 部分在 select 部分之前执行,因此您不能在 customer.roundedrate 中引用别名 where声明。

试试这个

SELECT *, round(customer.rate,-1) as roundedrate
FROM customer INNER JOIN rate ON round(customer.rate,-1) = rate.rate

http://sqlfiddle.com/#!9/e94a60/2