sql - SQLite 为表中的每个类别或查询中的查询创建一个表
问题描述
我的数据库有一张桌子 - “汽车”
它具有以下列: 制造商 | 型号 | 价格
我想做一个查询,返回每个汽车制造商的汽车表,其中价格比该制造商的平均价格低 20%
- 我想知道是否有办法在没有 for 循环的情况下做到这一点
- 最初为每个汽车制造商创建一个表会更有效吗?
- 只创建一个结果表会更有效吗?并由汽车制造商对其进行分类
解决方案
如果您想要 SQL,请使用相关子查询:
select c.* from cars c
where c.price < 0.8 * (
select avg(price) from cars
where manufacturer = c.manufacturer
)
或加入:
select c.*
from cars c inner join (
select manufacturer, avg(price) price
from cars
group by manufacturer
) t on t.manufacturer = c.manufacturer and c.price < 0.8 * t.price
或带有AVG()
窗口功能:
select t.manufacturer, t.model, t.price
from (
select *,
avg(price) over (partition by manufacturer) avgprice
from cars
) t
where t.price < 0.8 * t.avgprice
推荐阅读
- javascript - 如何从样式化组件(React)访问 CSS 值?
- sql - 根据多个可能数组中的存在更新表值 (SQL)
- spring-integration - Spring Integration 5.07 使用 Java DSL 桥接两个 JMS 队列
- python - 在python中查找列表之间的日期时间差异
- swift - 逗号分隔的带有 2 位小数的数字 - swift
- java - JPQL 或未按预期工作
- ios - react-native iOS App在调试方案中运行时接收firebase动态链接,但在发布方案中运行时不接收
- php - 当我更改 Homestead 日期时,Laravel Csrf 令牌失败
- python - Python 导入并运行位于不同目录中的 python 脚本
- google-shopping-api - 列出不返回资源的函数