如何使用sql获取最常见和最不常见的值?

时间:2019-02-14 09:38:56

标签: standard-sql

输入表:

a b c
1 2 1
1 2 1
1 2 2
1 3 1
1 3 3
1 3 3
2 2 5
2 2 5
2 2 7
2 3 5
2 3 8
2 3 8

预期输出:

a b min max
1 2 2 1
1 3 1 3
2 2 7 5
2 3 5 8

逻辑:按col acol b分组,从col c中获得最不通用和最通用的值。

在上面的a = 1b = 2的示例中,col c的最小公共值为2,col c的最大公共值为1,这在输出的第一行中进行了描述。 / p>

当前,我能够通过查询来计数每个值的出现

select a, b, c, count(c) from table group by a, b, c

1 个答案:

答案 0 :(得分:0)

答案很晚,但是我觉得它很有趣(很有趣)。
您尚未标记任何特定的rdbms,但是由于大多数数据库都可以使用CTE:

with 
  counters as (
    select
      a, b, c, count(*) counter
    from tablename
    group by a, b, c
  ),
  minmax as (
    select
      a, b, min(counter) mincounter, max(counter) maxcounter
    from counters 
    group by a, b
  )    
select 
  c.a, c.b, 
  max(case c.counter when m.mincounter then c.c end) min,
  max(case c.counter when m.maxcounter then c.c end) max
from counters c inner join minmax m
on m.a = c.a and m.b = c.b and c.counter in (m.mincounter, m.maxcounter)
group by c.a, c.b

请参见demo
结果:

| a   | b   | min | max |
| --- | --- | --- | --- |
| 1   | 2   | 2   | 1   |
| 1   | 3   | 1   | 3   |
| 2   | 2   | 7   | 5   |
| 2   | 3   | 5   | 8   |