SQL:选择最常出现的与不同列对应的值

时间:2018-05-14 15:38:23

标签: sql postgresql

有人能指出我解决问题的正确方法。 我有一张桌子 -

+------+-------+--------------------------------------+
| id   | num   | date                                 |
+------+-------+--------------------------------------+
| a    | 1     | 2011-08-12T20:17:46.384Z             |
| a    | 1     | 2011-08-12T20:18:46.384Z             |
| a    | 2     | 2011-08-12T20:19:46.384Z             |
| a    | 2     | 2011-09-12T20:17:46.384Z             |
| c    | 3     | 2011-09-12T20:18:46.384Z             |
+------+-------+--------------------------------------+

现在,对于给定的日期范围,我想获取列" num"的最大值,用于" id"值。

范围(2011-08-12T00:00:00.000Z至2011-08-12T23:59:00.000Z)的结果应为

| a    | 1     | 090518                               |

基本上,我想要在给定的dateTime范围内对应于id的列的最大值。

我将使用PostgreSQL。

3 个答案:

答案 0 :(得分:0)

ANSI标准公式 - 假设date存储为日期/时间 - 将是:

select num, count(*)
from t
where date >= date '2018-05-09' and
      date < date '2018-05-10'
group by num
order by count(*) desc
fetch first 1 row only;

请注意,大多数数据库都会有一些这种语法的微小变化。此外,如果存在联系,则仅返回值。

编辑:

问题是单数:

  

我想获取列“num”的最大值,以获取“id”值。

但是,如果你想要一个平局的所有等价值,那么:

select num, cnt
from (select num, count(*) as cnt,
             rank() over (order by count(*) desc) as seqnum
      from t
      where date >= date '2018-05-09' and
            date < date '2018-05-10'
      group by num
     ) n
where seqnum = 1;

答案 1 :(得分:0)

这对你有什么用?

 select max(c.id) id, c.num, c.cnt  from 
(select id, max(cnt) cnt from (
Select id, num, count(*) cnt 
from #temp 
group by id, num)a  group by id)b 
join 
(Select id, num, count(*) cnt 
from #temp 
group by id, num)c on b.id=c.id and b.cnt=c.cnt
group by c.num, c.cnt 

答案 2 :(得分:0)

这应该返回这样的内容:

| id | num | occurrences |
select id,num,count(num) as [occurrences]
from MyTable 
where  id = 'a' /* Given id */
and [date]  >= '2011-08-12T00:00:00.000Z' AND [date]  <= '2011-08-12T23:59:00.000Z' /* Given Range */
group by id,num
order by [occurrences] DESC