2017-04-26 72 views
0

我想要一個列出所有狀態爲「活動」的客戶的查詢。該查詢將返回標記爲活動的客戶列表。我的問題是我迷失在查詢引用其他表的表上。這是我的模式。PostgreSQL查詢模式

CREATE TABLE Customer (
    ID BIGSERIAL PRIMARY KEY NOT NULL, 
    fNAME TEXT NOT NULL, 
    lNAME TEXT NOT NULL, 
    create_date DATE NOT NULL DEFAULT NOW() 
); 

CREATE TABLE CustomerStatus (
    recordID BIGSERIAL NOT NULL, 
    ID BIGSERIAL REFERENCES Customer NOT NULL, 
    status TEXT NOT NULL, 
    create_date DATE NOT NULL DEFAULT NOW() 
); 

INSERT INTO Customer (fNAME, lNAME) VALUES ('MARK', 'JOHNSON'), ('ERICK', 'DAWN'), ('MAY', 'ERICKSON'), ('JESS', 'MARTIN'); 

INSERT INTO CustomerStatus (ID, status) VALUES (1, 'pending'), (1, 'active');  

INSERT INTO CustomerStatus (ID, status) VALUES (2, 'pending'), (2, 'active'), (2, 'cancelled');  

INSERT INTO CustomerStatus (ID, status) VALUES (3, 'pending'), (3, 'active'); 

INSERT INTO CustomerStatus (ID, status) VALUES (4, 'pending'); 
+0

有模式中的一些奇怪的事情。 1. Customer.ID NOT NULL約束是多餘的。 2.爲什麼CustomerStatus.ID輸入BIGSERIAL?我想,它應該是BIGINT。 3.主要問題(你應該解釋它) - 1客戶可以有多個CustomerStatus?如果是(並且CustomerStatus表類似CustomerStatusHistory),則將約束UNIQUE(ID,create_date)添加到CustomerStatus。否則,約束是UNIQUE(ID),客戶只能擁有一個狀態。 – Eugene

+0

固定感謝調用冗餘 – MarkM

回答

0

我鼓起勇氣假設RECORD_ID串行=>最新的ID將是最後的,產生這種QRY:

t=# with a as (
    select *, max(recordid) over (partition by cs.id) 
    from Customer c 
    join CustomerStatus cs on cs.id = c.id 
) 
select * 
from a 
where recordid=max and status = 'active'; 
id | fname | lname | create_date | recordid | id | status | create_date | max 
----+-------+----------+-------------+----------+----+--------+-------------+----- 
    1 | MARK | JOHNSON | 2017-04-27 |  2 | 1 | active | 2017-04-27 | 2 
    3 | MAY | ERICKSON | 2017-04-27 |  7 | 3 | active | 2017-04-27 | 7 
(2 rows) 

Time: 0.450 ms