问题描述
我一直在尝试查询每个城市的流行类型。我只想获取突出显示的行。我尝试在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)
我尝试了以下查询。
解决方法
我没有数据集可以对此进行测试,但是您应该只需要向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)