如何在PostgreSQL中使用Count作为标准

时间:2016-06-08 19:38:20

标签: postgresql

我有一个现有的table1,其中包含" account"," tax_year"和其他领域。当CONCAT(account,tax_year)的频率为1并满足WHERE子句时,我想创建一个table2,其中包含来自table1的记录。

例如,如果table1如下所示:

account year
aaa 2014
ddd 2015

表2应为:

DROP TABLE IF EXISTS table1;
CREATE table2 AS
SELECT 
    account::text, 
    tax_year::text,
    building_number,
    imprv_type,
    building_style_code,
    quality,
    quality_description,
    date_erected,
    yr_remodel,
    actual_area,
    heat_area,
    gross_area,
    CONCAT(account, tax_year) AS unq
FROM table1
WHERE imprv_type=1001 and date_erected>0 and date_erected IS NOT NULL and quality IS NOT NULL and quality_description IS NOT NULL and yr_remodel>0 and yr_remodel IS NOT NULL and heat_area>0 and heat_area IS NOT NULL
GROUP BY account, 
    tax_year,
    building_number,
    imprv_type,
    building_style_code,
    quality,
    quality_description,
    date_erected,
    yr_remodel,
    actual_area,
    heat_area,
    gross_area,
    unq
HAVING COUNT(unq)=1;

这是我的剧本:

struct num* deleteCell(struct num* point, int numdelete) {
  if (point == NULL) {
     return NULL;
  }

  if (point->number == numdelete) { 
    num* tempdelete = point->pNext;
    free(point);
    return deleteCell(tempdelete, numdelete);
  }

  point->pNext = deleteCell(point->pNext, numdelete);
  return point;
}

我花了两天时间,但仍然无法弄清楚如何做到正确。谢谢你的帮助!

2 个答案:

答案 0 :(得分:0)

COUNT() = 1相当于NOT EXISTS(another with the same key fields)

SELECT 
    account, tax_year
    -- ... maybe more fields  ...
FROM table1 t1
WHERE NOT EXISTS ( SELECT *
    FROM table1 nx
    WHERE nx.account = t1.account  -- same key field(s)
    AND nx.tax_year = t1.tax_year
    AND nx.ctid <> t1.ctid         -- but a different row!
    );

注意:我用复合匹配键替换了COUNT(CONCAT(account, tax_year)关键字段的连接。

答案 1 :(得分:0)

(account, tax_year)中使用table1对的正确方法:

select account, tax_year
from table1
where imprv_type=1001 -- and many more...
group by account, tax_year
having count(*) = 1;

所以你应该尝试:

create table table2 as
select * 
from table1
where (account, tax_year) in (
    select account, tax_year
    from table1
    where imprv_type=1001 -- and many more...
    group by account, tax_year
    having count(*) = 1
    );