mysql - SQL新手: How to compare all rows within a column to reflect how many rows are "cheaper/less than" the respective row?

标签 mysql sql count case

我遇到麻烦的地方
我相信我需要使用 COUNT;但是,我不知道如何将一行与同一列中的每一行进行比较,然后计算有多少行比相应行少/便宜。提前谢谢您!

这是我试图解决的官方问题:
“使用示例架构,编写一条 SQL 语句,该语句将返回 Products 表中的所有产品,并统计有多少其他产品比该产品的价格便宜。”

Image example of solution

Image of all tables relative to the question


到目前为止我的代码...

SELECT 
product_id, 
product_name, 
product_price, 
CASE WHEN product_price >????
END AS products_cheaper_count  
FROM [Products]

最佳答案

你是对的,你需要在内部SELECT查询中使用COUNT来获取所有比当前产品便宜的产品的数量,例如:

SELECT p.product_id, p.product_name, p.product_price,
(SELECT COUNT(*) FROM products WHERE product_price < p.product_price) AS products_cheaper_count
FROM products;

关于mysql - SQL新手: How to compare all rows within a column to reflect how many rows are "cheaper/less than" the respective row?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42035095/

相关文章:

java - 从 MySQL 读取文本文件

MySQL 查询 : Get new customers in the month

sql - LIKE 对非英文字母不区分大小写

sql - 使用 t-sql 计算二进制类型的真位计数

php - 通过导入将图像上传到xampp中的数据库

python - 安全性:绕过使用 URL 输入的登录

php - 如果有任何服务绑定(bind)到另一个表中的类别 ID,则从表中获取类别

r - 在矩阵的上限范围内逐行计数 N 次出现

mysql - 计算链接表中的重复项

mysql - 如何在 MacOS 中恢复 mysql root 密码