使用子查询postgresql

使用子查询postgresql,sql,postgresql,Sql,Postgresql,我想在我的两个表Revolution和contact之间进行内部联接,其中Revolution表cat列的值为'cat1',total_uu属于前20% 算法: 此列表中cat=cat1和total_u>0上的过滤器每年仅获取属于前20%总数的过滤器。然后用contact进行连接_ create table turnover ( cod integer, cat varchar(40), date_ date, cash integer, CB

我想在我的两个表Revolution和contact之间进行内部联接,其中Revolution表cat列的值为'cat1',total_uu属于前20%

算法:

此列表中cat=cat1和total_u>0上的过滤器每年仅获取属于前20%总数的过滤器。然后用contact进行连接_

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

create table contact (
cod    integer,
date_     date,
Type_      varchar(40),
Mail_      integer,
sms         integer, 
phone integer,
total_      integer,
CONSTRAINT cnt UNIQUE(cod, date_, type_)); 

 select t.cod, t.cat, t.date_, t.total_,
   c.cod, c.date_, c.type_, c.total_
  from (select t.*
   from turnover t
   where t.cat = 'cat1' and t.total_ > 0
   ) t Inner join
   contact c
   on t.cod = c.cod
   group by t.date_;
在Postgreaql中,您可以使用行数窗口函数和计数窗口函数来实现它。请尝试以下查询:

select
cod, cat, t_date, total_, c_date, type_, total_
from
(
select 
   t.cod, 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.cod = c.cod
where t.cat = 'cat1' and t.total_ > 0
) t1
where t1.rn/t1.cnt<=0.20

您具体描述的是:

select t.cod, t.cat, t.date_, t.total_,
       c.cod, c.date_, c.type_, c.total_
from (select t.*,
             row_number() over (order by t.total_ desc) as seqnum,
             count(*) over () as cnt
      from turnover t
      where t.cat = 'cat1' and t.total_ > 0
     ) t join
     contact c 
     on t.cod = c.cod
where t.seqnum <= 0.20 * t.cnt;

有什么问题?顺便说一句:您不需要子查询;你可以把这两个表连接起来,这就是你想要达到的目标。请添加一些样本数据和所需输出以及您的算法HMI无法执行20%@wildplasser。我添加了我的代码。感谢you@alkilesh米什拉非常感谢你。请再问一个问题,正如我提到的,我必须每年做一次。让我们注意一下我的专栏日期:2019-01-012018-01-012017-01-012013-01-012012-01-01我是否应该在末尾简单地按t.date添加group?Dankeyearly的意思是你是否只想要一年?我的意思是每年@Akhilesh Mishra添加了所需的changes@biwia . . . 打字错误。你是说用seqnum代替rn吗@戈登·林诺夫
select t.cod, t.cat, t.date_, t.total_,
       c.cod, c.date_, c.type_, c.total_
from (select t.*,
             ntile(5) over (order by t.total_ desc) as tile
      from turnover t
      where t.cat = 'cat1' and t.total_ > 0
     ) t join
     contact c 
     on t.cod = c.cod
where tile = 1;