简体   繁体   中英

Postgres Syntax inner join update and temp table

I'm using pg 9.3 and am wondering how I could do this in one statement, maybe even without a temp table. This seems a little messy to me.

create temp table docUse (
docid int primary key, 
name text, cnt int, 
mindate timestamp, 
maxdate timestamp);

insert into docuse (docid,cnt) 
    select documenttypeID, count(documenttypeID) from AllDocs group by documenttype;

update docuse set name = DocName from documenttype where documenttypeid = docid;

update docuse 
set mindate = _minDate, maxdate = _MaxDate from(
     Select min(Creation_Date) _mindate, max(Creation_Date) _MaxDate, docid did
    from AllDocs inner join docuse on documenttypeid = docid group by docid
) foo where did = docid;

A sample return row looks like

761,Invoice,598236,1/1/2000 12:00:00 am, 2/19/2016 3:15:54 pm

Try:

insert into docuse (docid,cnt, mindate, maxdate, name  ) 
SELECT x.documenttypeID, x.cnt, x.mi, x.mx,
       ( SELECT DocName d from documenttype where d.documenttypeid = x.documenttypeID)
FROM ( 
    select documenttypeID, 
           count(documenttypeID) as cnt,
           min(Creation_Date) as mi,
           max(Creation_Date) as mx
    from AllDocs a
    group by documenttype
) x;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM