【问题标题】:sql: Select count(*) - nth record from each groupsql: Select count(*) - 每组的第 n 条记录
【发布时间】:2019-09-13 20:16:31
【问题描述】:

我按tenant_id 分组。我想从每个 GROUPBY 组中选择 count() - 第 1000 条记录(按 _updated 时间排序),用于 count() 大于 1000 的组。如下:

select t1.tenant_id,
(select temp._updated
 from trace temp
 where temp.tenant_id = t1.tenant_id
 order by _updated limit 1 offset   
    count(*) - 1000
) as timekey 
from fgc.trace as t1
group by tenant_id 
having count(*)  > 1000;

但这是不允许的,因为 count(*) 不能在子查询中使用。

所以我尝试了以下方法,但仍然无法正常工作,因为我无权访问 t1,因为这不是连接。

select t1.tenant_id,
(select temp._updated
 from trace temp
 where temp.tenant_id = t1.tenant_id
 order by _updated limit 1 offset   
    (select count(*)-1000 
     from trace t2
     group by tenant_id 
     having t2.tenant_id = t1.tenant_id)
) as timekey 
from fgc.trace as t1
group by tenant_id 
having count(*)  > 1000;

那么我怎样才能得到以下内容呢?

  tenant_id |             timekey               
+-----------+----------------------------------+
  n7ia6ryc  | 2019-07-23 23:09:49.951406+00:00  

【问题讨论】:

  • 我想你只想在这里使用 row_number() - 但我不确定你需要什么。您想要第 1000 条之后的每条记录吗?
  • 假设给定的tenant_id下有1014条记录。我想(最终)删除最旧的 14 条记录,以便相关租户只有 1000 条记录。因此,我得到了第 (1014 - 1000) 条记录的时间戳,然后计划使用小于实际删除的时间戳。 @霍根
  • 你想要第 1000 个之后的所有 id 吗?
  • 不完全。我想要(每个租户的总数 - 1000)th 时间戳。只有一个时间戳。 @霍根
  • @Hogan 编辑了问题以澄清。

标签: sql cockroachdb


【解决方案1】:

你似乎想要ROW_NUMBER()Cockroach supports windows functions,所以:

SELECT updated
FROM (
    SELECT
        tenant_id, 
        updated,
        ROW_NUMBER() OVER(PARTITION BY tenant_id ORDER BY updated DESC) rn
    FROM trace
) x WHERE rn = 1001

对于每个tenant_id,这将返回第 1001 条最近记录的时间戳。如果给定租户的记录少于 1000 条,则它不会出现在结果中。

【讨论】:

    【解决方案2】:
    select x.tenant_id
    from (
      select t.tenant_id,
             row_number() over (partition by t.tenant_id order by t.timekey) as tenant_number
      from fgc.trace as t
    ) x
    where x.tenant_number > 1000
    group by x.tenant_id 
    

    只有一个时间戳看起来像这样:

    select min(x.timekey) as min_timestamp
    from (
      select t.tenant_id, t.timekey,
             row_number() over (partition by t.tenant_id order by t.timekey) as tenant_number
      from fgc.trace as t
    ) x
    where x.tenant_number > 1000
    

    请注意,在这里分组并不重要,因为每一行只能在一个组中,而您只能查看一行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-04
      • 1970-01-01
      • 2023-03-15
      • 1970-01-01
      • 2019-08-03
      • 2021-11-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多