返回选定组中某个值的计数并在其他组中计数的 SQL

问题描述 投票:0回答:1

我有下表:

create table tablex (fileID int, file varchar(10), name varchar(10));
insert into tablex (fileID, file, name) values (1, 'file1' , 'AAA'),(1, 'file1' , 'AAA'),(1, 'file1' , 'AAA'),(2, 'file2' , 'AAA'),(2, 'file2' , 'AAA'),(2, 'file2' , 'AAA'),(1, 'file1' , 'BBB'),(1, 'file1' , 'BBB'),(2, 'file2' , 'BBB'),(2, 'file2' , 'BBB'),(3, 'file3' , 'BBB'),(3, 'file3' , 'BBB'),(1, 'file1' , 'CCC'),(1, 'file1' , 'CCC');

tablex

fileID | file | name
1 | file1 | AAA
1 | file1 | AAA
1 | file1 | AAA
2 | file2 | AAA
2 | file2 | AAA
2 | file2 | AAA
1 | file1 | BBB
1 | file1 | BBB
2 | file2 | BBB
2 | file2 | BBB
3 | file3 | BBB
3 | file3 | BBB
1 | file1 | CCC
1 | file1 | CCC

我期望只获取出现在多个文件中的名称,然后统计id最大的文件中出现的次数,以及其他文件中出现的次数。例如

AAA - 文件 2 中出现 3 次,其他文件中出现 3 次

BBB - 在文件 3 中出现 2 次,在其他文件中出现 4 次

我正在尝试使用窗口函数(仍在学习),但不确定这种方法是否是最好的方法,因为我必须添加一个独特的方法才能使其工作

select distinct t.name, count(t.name) over (partition by t.name) countAll,
       count(t.name) over (partition by t.name, fileId) countLatestFile,
       count(t.name) over (partition by t.name) - count(t.name) over (partition by t.name, fileId) countOthers
  from tablex t
  join (select name from tablex group by name having count(distinct fileId)  > 1) tdups
   on t.name = tdups.name;

还有其他想法吗?

mysql sql window-functions
1个回答
0
投票

这是一种使用窗口函数的方法

dense_rank

cte
用于按文件 ID 排序的名称获取排名。
cte2
从每个名称(具有最大排名)获取最新文件。

然后我们加入数据以获得预期的输出:

with cte as (
  select *, dense_rank() over (partition by name order by fileID) rn,
           count(name) over (partition by name) countAll
  from tablex
),
cte2 as (
  select name, max(rn) max_rn
  from cte
  group by name
  having max(rn) > 1
)
select c.name, max(c.countAll) as countAll, max(c.file) as latestFile, count(c.name) as countLatestFile, 
       max(c.countAll) - count(c.name) as countOthers
from cte c
inner join cte2 c2 on c.rn = c2.max_rn and c.name = c2.name
group by c.name

这里演示

© www.soinside.com 2019 - 2024. All rights reserved.