我有类似于这个例子的事务数据:
Name | Price
George | 20
George | 20
George | 20
George | 30
Paul | 20
Paul | 20
Paul | 30
Paul | 30
Paul | 35我需要按用户进行分组,并按一般事务的数量进行排序,但在这组用户中,还需要根据按该价格进行的交易数量进行价格排序。我需要这个结果:
Name | Price | Count
Paul | 20 | 2
Paul | 30 | 2
Paul | 35 | 1
George | 20 | 3
George | 30 | 1更新
它位于MySQL 5.5数据库中。我需要用Laravel对fluent进行查询,但是在SQL中使用它是一个很大的进步。
提前谢谢。
发布于 2020-01-10 17:02:57
SELECT t1.*
FROM ( SELECT name,
price,
COUNT(*) cnt
FROM srctable
GROUP BY name, price ) t1
JOIN ( SELECT name,
COUNT(*) tcnt
FROM srctable
GROUP BY name ) t2 USING (name)
ORDER BY tcnt DESC,
cnt DESC;发布于 2020-01-10 15:54:07
这就是你要的。它可以在MySQL 8.x中完成。所需的双重排序要求使用两个表表达式,如下所示:
select
x.name, x.price, x.cnt
from (
select name, price, count(*) as cnt
from t
group by name, price
) x
join (
select name, row_number() over(order by cnt desc) as ob
from (
select name, count(*) as cnt
from t
group by name
) y
) z on x.name = z.name
order by z.ob, x.cnt desc结果:
name price cnt
------ ----- ---
Paul 20 2
Paul 30 2
Paul 35 1
George 20 3
George 30 1作为参考,我使用的数据脚本是:
create table t (
name varchar(10),
price int
);
insert into t (name, price) values
('George', 20),
('George', 20),
('George', 20),
('George', 30),
('Paul', 20),
('Paul', 20),
('Paul', 30),
('Paul', 30),
('Paul', 35);https://stackoverflow.com/questions/59684895
复制相似问题