首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Vertica/vSQL“每天选择10行,按顺序排列,并在某个组上

Vertica/vSQL“每天选择10行,按顺序排列,并在某个组上
EN

Stack Overflow用户
提问于 2012-07-18 01:58:43
回答 1查看 5.1K关注 0票数 0

我有Vertica数据库,有很多带有日期(时间戳)和更多属性的记录。例如,'testTable‘看起来像这样

代码语言:javascript
复制
a varchar(255)
b int
timestamp bigint

我需要找到一段时间(比方说1月1日到1月15日)每一天的前10名的sum(b),这些日期可以由用户指定。

迭代查询将是什么样子的?粗略的方法可能是在中间包含UNION ALL的单个SELECT语句。

代码语言:javascript
复制
select a, sum(b) from testTable where TO_TIMESTAMP( timestamp ) between '2012-01-01 05:10:00' and '2012-01-02 05:10:00' group by a order by sum(b) desc LIMIT 10
UNION ALL
select a, sum(b) from testTable where TO_TIMESTAMP( timestamp ) between '2012-01-02 05:10:00' and '2012-01-03 05:10:00' group by a  order by sum(b) desc LIMIT 10
UNION ALL
select a, sum(b) from testTable where TO_TIMESTAMP( timestamp ) between '2012-01-03 05:10:00' and '2012-01-04 05:10:00' group by a order by sum(b) desc LIMIT 10
..
..
..
UNION ALL
select a, sum(b) from testTable where TO_TIMESTAMP( timestamp ) between '2012-01-14 05:10:00' and '2012-01-15 05:10:00' group by a order by sum(b) desc LIMIT 10 ;

但我希望它更通用,用户可以运行具有两个给定日期的脚本。

EN

回答 1

Stack Overflow用户

发布于 2012-07-25 22:15:27

语法可能有点不对劲……我没有Vertica来测试。

代码语言:javascript
复制
select day, a, tot
from 
   (
   select 
      *,
      ROW_NUMBER() OVER (PARTITION BY tt4.day) as row_number
   from
      (
      select
         ts as day, 
         tt1.a, 
         sum(tt1.b) as tot
      from 
         testTable tt1, 
         ( select distinct date(TO_TIMESTAMP(tt2.timestamp)) as ts
           from   testTable tt2
           where  date(TO_TIMESTAMP(tt2.timestamp)) between cast('2012/01/01' as date) and cast('2012/01/15' as date) ) as tt3
      where 
         date(TO_TIMESTAMP(tt1.timestamp)) = tt3.ts
      group by 
         date(TO_TIMESTAMP(tt1.timestamp)), 
         tt1.a
      order by 
         date(TO_TIMESTAMP(tt1.timestamp)),
         sum(tt1.b) desc,
         tt1.a
      ) as tt4
   ) as tt5
where 
   tt5.row_number <=10
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11528182

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档