我有下表:
我想在一个查询(SQLite)中计算每辆车的平均里程数。我该怎么做?
这是我最接近的:
SELECT Car, Mileage, ROW_NUMBER() OVER (PARTITION BY Car ORDER BY Mileage) RowNum FROM car_table ORDER BY Car, Mileage;
我的预期输出是:
汽车 |中位里程
您可以使用窗口函数 ROW_NUMBER()、COUNT() 和 AVG() 来完成:
SELECT DISTINCT Car,
AVG(
CASE counter % 2
WHEN 0 THEN CASE WHEN rn IN (counter / 2, counter / 2 + 1) THEN mileage END
WHEN 1 THEN CASE WHEN rn = counter / 2 + 1 THEN mileage END
END
) OVER (PARTITION BY car) median
FROM (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY car ORDER BY mileage) rn,
COUNT(*) OVER (PARTITION BY car) counter
FROM car_table
)
或者:
SELECT DISTINCT Car,
AVG(CASE WHEN rn IN (counter / 2 + 1, counter / 2 + 1 - (counter % 2 = 0)) THEN mileage END)
OVER (PARTITION BY car) median
FROM (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY car ORDER BY mileage) rn,
COUNT(*) OVER (PARTITION BY car) counter
FROM car_table
)
查看演示。
结果:
汽车 | 中位数 |
---|---|
本田 | 11.85 |
丰田 | 9.8 |