最小分组与Max

时间:2016-01-13 11:43:22

标签: sql sql-server

我有一个关于如何编写下表查询的问题:

File#        Test#        Phase#      
----------  ----------  ----------
A           1           1         
A           1           2         
A           2           1     

结果应如下所示:

  File#        Test#        Phase#      
----------  ----------  ----------
  A             2           1     

我想做的是让测试与**最低阶段* !!

进一步解释:

测试1有两个阶段(阶段1,阶段2)

测试2只有一个阶段(阶段)

因此,对于文件A,阶段数最少的测试是测试2

我的踪迹:

我能够通过以下查询获取每个测试的阶段的最大值:

Select File, Test , Max(Phase) as MaxPhases
From table
Group by File, Test

然后,我想到了结果的最小值,它应该是这样的:

Select Min (t1.MaxPhases ) 
From ( Select File, Test , Max(Phase) as MaxPhases
    From table
    Group by File, Test) t1

但是我无法添加File#的其他信息,测试#...我只能采取最低限度的信息..

1 个答案:

答案 0 :(得分:1)

您可以使用分析功能COUNT OVER。因此,您可以获得每个测试的相位计数以及原始记录。然后选择顶级测试的记录(所有测试的最小计数)。然后按测试和阶段排序,以按所需顺序显示记录。

select
  test, phase
from
(
  select top(1) with ties 
    test, phase
  from
  (
    select test, phase, count(*) over (partition by test) as cnt
    from table
    where file = 'A'
  ) test_records_with_count
  order by cnt
) top_test_records
order by test, phase
;

这与RANK OVER相同,而不是TOP WITH TIES:

select
  test, phase
from
(
  select
    test, phase, rank() over (order by cnt) as rnk
  from
  (
    select test, phase, count(*) over (partition by test) as cnt
    from table
    where file = 'A'
  ) test_records_with_count
) test_records_ranked
where rnk = 1
order by test, phase
;

可以轻松调整第二种方法,以便获得多个文件的结果。

还有其他方法可以解决这个问题。例如,您可以完全不使用分析函数,这将涉及多次读取表格。