我现有的表1包含“帐户”和“税年”。我想用表1中的两个变量创建一个新的表2,并添加两个新变量(unq和frequency)。
例如,假设下表是查询的中间结果。帐户和年份来自现有表1。unq和频率由查询生成,公式为:unq=会计和纳税年度,频率=计数(unq)

account year    unq frequency
aaa 2014    aaa2014 1
bbb 2014    bbb2014 2
bbb 2014    bbb2014 2
ccc 2015    ccc2015 2
ccc 2015    ccc2015 2
ddd 2014    ddd2014 1
ddd 2015    ddd2015 1
ddd 2016    ddd2016 1

最后,查询应返回以下结果:
account year    unq frequency
aaa 2014    aaa2014 1
ddd 2014    ddd2014 1
ddd 2015    ddd2015 1
ddd 2016    ddd2016 1

这是我的代码,不起作用。我对PostgreSQL相当陌生。
CREATE TABLE table2 AS
SELECT account::text,
       tax_year::text,
    concat(account,tax_year) AS unq,
    Count(unq) AS frequency
FROM table1
GROUP BY unq
HAVING Count(unq)=1;

最佳答案

如果您的表与显示的表相似,为什么要聚合您可以使用where

CREATE TABLE table1 AS
    SELECT account::text, tax_year::text, unq AS unique, frequency
    FROM table2
    WHERE frequency = 1;

如果您的表包含accounttax_year并且您要进行计算:
CREATE TABLE table1 AS
    SELECT account::text, tax_year::text,
           CONCAT(account, tax_year) AS unique,
           COUNT(*) as frequency
    FROM table2
    GROUP BY account, tax_year
    HAVING COUNT(*) = 1;

10-02 18:05