簡體   English   中英

PSQL:如何獲取另一個列在一個列組中每個值的記錄計數

[英]PSQL : How to get the record count of each value in a column group by another column

PSQL:我的主表有2000萬條記錄,當我運行select時,它將運行數小時。 有沒有辦法更好地寫這個陳述?

我的桌子:

Select * from lookup limit 10;
-------------------------
month      id
2010-01     598362
2010-01     598343
2010-02     598343
2010-02     988343
2010-03     789624
2010-04     789624
2010-05     789624
2010-06     899624 

從表我試圖找到

  1. 該月不同ID的計數
  2. 前2個月中也存在的不同ID的計數

我的select語句(如下)適用於小數據(最多100,000條記錄)

--PSQL
select  month, 
    count (distinct id)id_ct,
    count (distinct case when (
                    id||(month-1) in (select distinct id||month from lookup ) 
                or  id||(month-2) in (select distinct id||month from lookup )  ) 
                    then id end) continuous_ct
    from lookup
    group by 1  order by 1

結果:

month     id_ct continuous_ct
 2010-01    2   0
 2010-02    2   1
 2010-03    1   0
 2010-04    1   1
 2010-05    1   1
 2010-06    1   0

謝謝!

如果您在id上有一個索引,那么這個簡單的查詢應該可以工作。 剛剛離開表本身。 http://sqlfiddle.com/#!15/133a9/7/0

select to_char(lookup_a.lookup_month, 'yyyy-mm'),
    count (distinct lookup_a.id) id_ct,
    count (distinct lookup_b.id) continuous_ct
from lookup lookup_a
left join lookup lookup_b 
    on lookup_b.id = lookup_a.id
    and lookup_b.lookup_month between lookup_a.lookup_month - interval '2 month'
    and lookup_a.lookup_month - interval '1 month'
group by 1  
order by 1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM