如何查询仅具有最高值的所有不同行?

问题描述

我一直在尝试查询每个城市的流行类型。我只想获取突出显示的行。我尝试在group by上使用MAX(),但给了我一个语法错误。

我的CTE查询如下,其基于dbeaver示例数据集:

with q_table
as 
(   select City,Genre,count(*) as counts
    from 
        (select c.City,g.Name as Genre
        from bus5dwr.dbeaver_sample.Customer c
        inner join bus5dwr.dbeaver_sample.Invoice i
            on i.CustomerId = c.CustomerId
        inner join bus5dwr.dbeaver_sample.InvoiceLine il
            on il.InvoiceId = i.InvoiceId 
        inner join bus5dwr.dbeaver_sample.track t
            on t.TrackId = il.TrackId 
        inner join bus5dwr.dbeaver_sample.Genre g
            on g.GenreId = t.GenreId 
        where Country = 'USA'
        ) as t2
    group by City,Genre)

我尝试了以下查询。

Screenshot of query output

解决方法

我没有数据集可以对此进行测试,但是您应该只需要向CTE添加ROW_NUMBER()函数即可获取所需的值。如:

with q_table
as 
(   select City,Genre,count(*) as counts,ROW_NUMBER() OVER(partition by City order by count(*) desc) RN
    from 
        (select c.City,g.Name as Genre
        from bus5dwr.dbeaver_sample.Customer c
        inner join bus5dwr.dbeaver_sample.Invoice i
            on i.CustomerId = c.CustomerId
        inner join bus5dwr.dbeaver_sample.InvoiceLine il
            on il.InvoiceId = i.InvoiceId 
        inner join bus5dwr.dbeaver_sample.track t
            on t.TrackId = il.TrackId 
        inner join bus5dwr.dbeaver_sample.Genre g
            on g.GenreId = t.GenreId 
        where Country = 'USA'
        ) as t2
    group by City,Genre)

SELECT City,Counts 
from q_table
WHERE RN=1
Order BY City
,

使用MAX应该可以。

编辑;添加了内部联接。感谢Gordon Linoff的观察,我的原始答案实际上并没有取得任何成就。

with q_table
as 
(   select City,count(*) as counts
    from 
        (select c.City,Genre)
SELECT a.City,a.Genre,a.counts
FROM q_table a
INNER JOIN (
    SELECT City,MAX(counts) counts
    FROM q_table
    GROUP BY City
) b ON a.City = b.City AND a.counts = b.counts;
,

尝试

 with q_table
 as 
 (select * from (
 (   select City,count(*) as counts
 from 
    (select c.City,g.Name as Genre
    from bus5dwr.dbeaver_sample.Customer c
    inner join bus5dwr.dbeaver_sample.Invoice i
        on i.CustomerId = c.CustomerId
    inner join bus5dwr.dbeaver_sample.InvoiceLine il
        on il.InvoiceId = i.InvoiceId 
    inner join bus5dwr.dbeaver_sample.track t
        on t.TrackId = il.TrackId 
    inner join bus5dwr.dbeaver_sample.Genre g
        on g.GenreId = t.GenreId 
    where Country = 'USA'
    ) as t2
 group by City,Genre)) as t3 where count in (select max(count) count from t3 group by city)

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...