Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/74.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在SQL中为联接使用舍入值_Sql_Join_Rounding - Fatal编程技术网

如何在SQL中为联接使用舍入值

如何在SQL中为联接使用舍入值,sql,join,rounding,Sql,Join,Rounding,我今天只是在学习SQL,我从来没有想过它有多有趣,直到我摆弄它。 我遇到了问题,需要帮助 我有两个表,客户和价格,详细信息如下 顾客 比率 然后我运行下面的查询,以便对customer.rate字段中的所有值进行四舍五入,然后将其与rate表进行内部联接 SELECT *, round(rate,-1) as roundedrate FROM customer INNER JOIN rate ON customer.roundedrate = rate.rate 它没有产生这样的结果: idc

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

我有两个表,客户和价格,详细信息如下

顾客

比率

然后我运行下面的查询,以便对customer.rate字段中的所有值进行四舍五入,然后将其与rate表进行内部联接

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;

注意:仅获取第一行是ANSI标准SQL,某些数据库不支持。MySQL使用限制。较旧版本的SQL Server改用select top 1。

我建议使用相关子查询:

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;

注意:仅获取第一行是ANSI标准SQL,某些数据库不支持。MySQL使用限制。较旧版本的SQL Server改用select top 1。

您的查询应产生“含糊列”错误,因为在引用roundrate,-1中的rate时未指定表名,这两个表中都存在

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

试试这个

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

您的查询应产生“不明确列”错误,因为在引用roundrate,-1中的rate时未指定表名,这两个表中都存在

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

试试这个

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

用您实际使用的数据库标记您的问题。我正在删除无关的数据库标记,但您应该添加正确的标记。使用实际使用的数据库标记您的问题。我正在删除无关的数据库标记,但您应该添加正确的标记。很抱歉,即使我没有研究子查询,我也尝试了该查询。它不适合我,我正在使用最新的mySQL v5.7.12 for windows。我是否必须更改某些内容?将fetch FIRST 1行仅更改为限制1。抱歉,即使我没有研究子查询,我也尝试过该查询。它不适合我,我正在使用最新的mySQL v5.7.12 for windows。我是否必须更改某些内容?将fetch FIRST 1行更改为limit 1。