首页 > 解决方案 > SQLite 为表中的每个类别或查询中的查询创建一个表

问题描述

我的数据库有一张桌子 - “汽车”

它具有以下列: 制造商 | 型号 | 价格

我想做一个查询,返回每个汽车制造商的汽车表,其中价格比该制造商的平均价格低 20%

  1. 我想知道是否有办法在没有 for 循环的情况下做到这一点
  2. 最初为每个汽车制造商创建一个表会更有效吗?
  3. 只创建一个结果表会更有效吗?并由汽车制造商对其进行分类

标签: sqlsqlite

解决方案


如果您想要 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

推荐阅读