如何在PostgreSQL中使用count作为选择标准

时间:2016-06-07 23:50:53

标签: postgresql

我有一个现有的table1包含“account”和“tax_year”。我想用table1中的两个变量创建一个新的table2,并添加两个新变量(unq和frequency)。

例如,假设下表是查询的中间结果。帐户和年份来自现有表1.查询使用以下公式生成unq和频率:unq = account& tax_year,frequency = count(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;

1 个答案:

答案 0 :(得分: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;