mysql - 尝试在 mySQL 的新列中将计算四舍五入到小数点后两位

标签 mysql sql mysql-workbench

所以我正在努力...

Write a SELECT statement that returns these column names and data from the Products table:

  • product_name
  • list_price
  • discount_percent
  • discount_amount
    • A column that’s calculated from the previous two columns
  • discount_price
    • A column that’s calculated from the previous three columns

Round the discount_amount and discount_price columns to 2 decimal places.

Sort the result set by discount price in descending sequence.

Use the LIMIT clause so the result set contains only the first 5 rows.

到目前为止我已经

USE my_guitar_shop;

SELECT product_name, list_price, discount_percent,
             CONCAT(discount_percent / 100 * list_price)
                AS discount_amount
FROM products

我能够返回 discount_amount,但无法将该列四舍五入到小数点后两位。

我该如何返回第二列?比如

ROUND(list_price - discount_amount, 2) 
AS discount_price  

它说它无法识别discount_amount?

最佳答案

使用ROUND()而不是CONCAT。

ROUND(discount_percent / 100 * list_price, 2)

第一个参数是要舍入的数字。第二个参数是四舍五入到多少位小数。

http://dev.mysql.com/doc/refman/5.7/en/mathematical-functions.html#function_round

Blockquote How would I also go about returning a second column? Such as

ROUND(list_price - discount_amount, 2) 
AS discount_price  

您不能重复使用这样的别名。我只是重复这个表达

ROUND(list_price - (discount_percent / 100 * list_price), 2) 
AS discount_price  

关于mysql - 尝试在 mySQL 的新列中将计算四舍五入到小数点后两位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36706884/

相关文章:

php - 我是否需要远程登录才能通过 php 脚本读取和写入 MySQL 数据库?

php - 在使用 PHP 时用 Parse.com 替换 MySQL 是否值得?

sql - 通过连接到满足某些条件的另一个表的最新记录来更新表

mysql - ssl连接错误: unknown error number

mysql - 将 MD5 哈希密码从一个 MySQL 传输到另一个

php - 使用 php 将图像上传到磁盘并在 mysql 数据库中保存图像名称

sql - RegEx:字符串中重复相同的元音 - Oracle SQL

sql - Sybase - 对 IN 子句使用参数

mysql - 打开包含 Blob 的脚本时出现文件编码问题

mysql 在新数据集上查询太慢 - mariaDB