我正在努力解决一个群体中的多数群体问题。举个例子,让我们说我的表看起来像这样:
+--------------------------------------------------+
| city | car_colour | car_type | qty |
+--------------------------------------------------+
| ------------------------------------------------ |
| manchester | Red | Sports | 7 |
| manchester | Red | 4x4 | 9 |
| manchester | Blue | 4x4 | 8 |
| london | Red | Sports | 2 |
| london | Blue | 4x4 | 3 |
| leeds | Red | Sports | 5 |
| leeds | Blue | Sports | 6 |
| leeds | Blue | 4X4 | 1 |
+--------------------------------------------------+
我试图找到一个纯粹的SQL解决方案,以便我可以看到:在每个城市,哪种颜色的汽车数量最多。
我能做到:
select city, cars, sum(qty)
from table
group by city, cars
得到:
+------------+------+----+
| manchester | red | 16 |
| manchester | blue | 8 |
| london | red | 2 |
| london | blue | 3 |
| leeds | red | 5 |
| leeds | blue | 7 |
+------------+------+----+
但无论如何我可以使用子查询来获得结果的最大值,这将返回每个城市的最大颜色,因此结果将显示:
+------------+------+
| manchester | red |
| london | blue |
| leeds | blue |
+------------+------+
我可以在我的Python脚本中进行这些计算,但更喜欢纯SQL解决方案。
希望这是有道理的,感谢您提前提供任何帮助:)
托米
答案 0 :(得分:3)
select distinct p.city, p.car_colour,sq.qty as qty
from ( select t.car_colour,t.city, sum(t.qty) as qty
from table1 t
group by t.car_colour,t.city
)p
join ( select q.city,max(q.qty) qty from
( select t.car_colour,t.city, sum(t.qty) as qty
from table1 t
group by t.car_colour,t.city
)q
group by q.city
)sq
on p.city=sq.city and p.qty=sq.qty
答案 1 :(得分:1)
这样可行,但可能会根据您使用的特定数据库进行改进:
select t.city, t.car_colour, a.qty
from table1 t
join (
select city, max(qty) qty
from (
select city, car_colour, sum(qty) qty
from table1
group by city, car_colour
) x group by city
) a on t.city = a.city
group by t.city, t.car_colour, a.qty
having sum(t.qty) = a.qty
order by t.city desc;
答案 2 :(得分:1)
如果您使用MS SQL:
DECLARE @t TABLE
(
city NVARCHAR(MAX) ,
color NVARCHAR(MAX) ,
qty INT
)
INSERT INTO @t
VALUES ( 'manchester', 'Red', 7 ),
( 'manchester', 'Red', 9 ),
( 'manchester', 'Blue', 8 ),
( 'london', 'Red', 2 ),
( 'london', 'Blue', 3 ),
( 'leeds', 'Red', 5 ),
( 'leeds', 'Blue', 6 ),
( 'leeds', 'Blue', 1 )
SELECT city , color
FROM ( SELECT city ,
color ,
SUM(qty) AS q ,
ROW_NUMBER() OVER ( PARTITION BY city ORDER BY SUM(qty) DESC ) AS rn
FROM @t
GROUP BY city , color
) t
WHERE rn = 1
输出:
city color
leeds Blue
london Blue
manchester Red