我有postgresql问题,我认为这很简单,但我无法概念化实现此目的所需的连接。
我有一个这种格式的表:
Company Agreement_num End_of_Agreement Contract_Amount ABC 2 (null) (null) ABC (null) 2015-01-10 10 ABC (null) 2015-09-01 12 ACME 2 (null) (null) ACME (null) 2014-06-05 5
我希望桌子看起来像这样:
Company Agreement_num End_of_Agreement Contract_Amount ABC 2 (null) (null) ABC 2 2015-01-10 10 ABC 2 2015-09-01 12 ACME 2 (null) (null) ACME 2 2015-06-05 5
基本上,只需将Agreement_num插入相应的公司。
为了让你知道我要去哪里,在此之后,我会做一个WHERE子句来只抓取那些没有达到End_of_Agreement的行:
Company Agreement_num End_of_Agreement Contract_Amount ABC 2 2015-09-01 12 ACME 2 2015-06-05 5
谢谢!
答案 0 :(得分:1)
我认为你可以使用类似的东西:
SELECT
t1.Company,
t2.Agreement_num,
t1.End_Of_Agreement,
t1.Contract_Amount
FROM
table
INNER JOIN
(
SELECT company, agreement_num
FROM table
WHERE agreement_num IS NOT NULL
) t2 ON
t1.company = t2.company
子查询将获取每个公司的agreement_num并在主查询中使用它。
您还可以使用窗口函数将其拉出来,从而缩小查询范围:
SELECT
company,
MAX(agreement_num) OVER (PARTITION BY company) as agreement_num,
end_of_agreement,
contract_amount
FROM
table;
答案 1 :(得分:0)
我认为你不想加入,我认为你需要使用MAX这样的聚合函数:
SELECT
Company,
MAX(Agreement_num) AS Agreement_num,
MAX(End_of_Agreement) AS End_of_Agreement,
MAX(Contract_Amount) AS Contract_Amount
FROM
yourtable
GROUP BY
Company
但不清楚Contract_Amount是否总是在增加。如果不是,并且您想要返回与最后一个End_Of_Aggreement关联的Contract_Amount,则可以将窗口函数与DISTINCT ON结合使用:
SELECT DISTINCT ON (company)
company,
MAX(Agreement_num) OVER (PARTITION BY Company) AS Agreement_num,
End_of_Agreement,
Contract_Amount
FROM
yourtable
ORDER BY
company,
end_of_agreement DESC NULLS LAST