我有一个大表 Audit
,其中包含数千条被拒绝的 claim 记录。每一个都来自一个供应商并且有一个拒绝原因和一个状态。只有 id
是唯一的。
id | denial | supplier | status
---|------------------|---------------|---------
1 | Duplicate claim | ACME | Adjusted
2 | Not authorized | Umbrella Corp | Adjusted
3 | Not authorized | Stark Ind. | Adjusted
4 | Rec'd after due | ACME | Override
5 | Duplicate claim | Stark Ind. | Adjusted
... etc
我需要的是按记录数列出的“已调整”状态声明的前 5 个拒绝原因,以及每个拒绝原因的记录数排名前列的供应商。
denial | cnt_denial | top_supplier | cnt_top_supplier
----------------|------------|---------------|-----------------
Not authorized | 917 | Stark Ind. | 351
Duplicate claim | 685 | Stark Ind. | 195
Not in contract | 525 | ACME | 216
Rec'd after due | 512 | Umbrella Corp | 500
Explosions | 349 | ACME | 231
我已经尝试了很多方法,主要是尝试采用其他有些类似的解决方案,但我在这里超出了我微薄的 SQL 知识并感到沮丧。我尝试过的几种解决方案在 MS Access (2010) 中不起作用。我一开始创建了两个查询,但我无法按照我需要的方式加入它们。
此查询准确返回我需要的拒绝原因数据:
SELECT TOP 5 denial, Count(*) AS cnt_denial
FROM Audit
GROUP BY status, denial
HAVING status="Adjusted"
ORDER BY Count(*) DESC;
并且此查询包含表中每个拒绝/供应商分组的计数。我不确定如何为每个拒绝原因找到顶级供应商,这看起来应该很简单,但我遇到了麻烦。编辑:这是我的主要问题。如果我能为每个拒绝原因找到顶级单一供应商,我就能找到加入。我试过使用 MAX 但还没有成功。/编辑
SELECT denial, supplier, Count(*) AS cnt_supplier
FROM Audit
GROUP BY denial, supplier, status
HAVING status="Adjusted"
ORDER BY Count(*) DESC;
我需要一个查询,因为我只是通过 ADO 从 Excel 传递它。任何帮助将不胜感激。
最佳答案
我不知道这是否是完全有效的 Access SQL。如果不是,则不需要太多调整:
select
d.denial,
d.cnt_denial,
ds.supplier as top_supplier,
ds.cnt_supplier as cnt_top_supplier
from
(
select top 5 denial, count(*) as cnt_denial
from Audit
where status = 'Adjusted'
group by denial
order by count(*) desc
) d
inner join
(
select denial, supplier, count(*) as cnt_supplier
from Audit
where status = 'Adjusted'
group by denial, supplier
) ds
on ds.denial = d.denial
where not exists (
select 1
from Audit as a2
where a2.status = 'Adjusted'
and a2.denial = ds.denial and a2.supplier <> ds.supplier
group by a2.supplier
having count(*) > ds.cnt_supplier
/* or count(*) = ds.cnt_supplier and a2.supplier < ds.supplier -- tiebreaker */
)
order by d.cnt_denial desc, ds.supplier
通过使用 top 5
,无论并列如何,它都只抓取了五行。然后每个组的前 1 名由子查询处理,在这种情况下,您将包含并列并可能在最终结果中检索超过 5 行。如果您需要的话,在拒绝级别上包含关系并不太难,或者打破关系并将它们排除在供应商排名中。
编辑:我将一些测试数据放在一起,打破平局似乎适用于 SQL Server。 http://rextester.com/ZEWJ43486
关于sql - 每个前 5 组的最高项(按记录计数)(Access SQL),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39353814/