首页 > 解决方案 > postgres:caseif值不存在sql

问题描述

我试图计算我的公司中营业额最好的前 10 名。我做了下面的代码。如果我的公司少于 10 家,我的问题是要做到最好。如果我的表营业额中有 < 10 家公司,我的查询将返回 NULL。如果我只有 8 家公司,我只想返回这 8 家公司中的佼佼者。(列总数)。

如果我不清楚,请告诉我!

代码

create table turnover (
id    integer,
cat     varchar(40),
date_      date,
total_     integer,
CONSTRAINT turnover_ UNIQUE(id, cat, date_));

create table contact (
id    integer,
date_     date,
Type_      varchar(40),
total_      integer,
CONSTRAINT cnt UNIQUE(id, date_, type_)); 
select
id, cat, t_date, total_, c_date, type_, total_
from
(
    select 
   t.id, t.cat, t.date_ "t_date",  t.total_,
   c.date_ "c_date", c.type_, c.total_
   count(*) over (partition by t.date_) as cnt,
   row_number() over (partition by t1.date_ order by t.total_ desc) as rn
    from turnover t
 inner join contact c on t.id = c.id
 where t.cat = 'cat1' and t.total_ > 0
 ) t1
 where t1.rn/t1.cnt<=0.10

标签: sqlpostgresql

解决方案


select
    id, 
    cat, 
    t1.t_date, 
    t1.total_, 
    c_date, 
    type_, 
    total_
from
(
   select 
       t.id, 
       t.cat, 
       t.date_ "t_date", 
       t.total_ as ttotal,
       c.date_ "c_date", 
       c.type_,
       c.total_,
       count(*) over (partition by t.date_) as cnt,
       row_number() over (partition by t.date_ order by t.total_ desc) as rn
   from turnover t
 inner join contact c on t.id = c.id
 --where t.cat = 'cat1' and t.total_ > 0
 ) t1
 limit 1

推荐阅读