psql查询计数应该是条件上的全局字段

时间:2017-01-22 10:01:03

标签: sql psql

表架构和数据:

CREATE TABLE aaa (
    nall integer NOT NULL,
    ladata date NOT NULL,
    txt text,
    CONSTRAINT aaa_pkey PRIMARY KEY (nall, ladata)
 )

数据:

2 | '2016-01-01' | 'a'
2 | '2016-02-02' | 'a'
5 | '2016-03-03' | 'a'
6 | '2016-03-03' | 'b'

查询:

select txt,
       count(txt),
       min(ladata),  
       (select  count(txt) from aaa where txt !='') 
from aaa
where ladata > (select MIN(ladata) from aaa ) and nall != 2
group by txt

http://sqlfiddle.com/#!15/db06b1/1

返回:

txt   count   min     count
b     1   March, 03 2016 00:00:00     1
a     3   March, 03 2016 00:00:00     3

我需要来自具有相同 txt 的行的部分计数,并且 nall 的行中的日期与2不同。

但是要从整个表中继续计数:

txt   count   min     count
b     1   March, 03 2016 00:00:00     4
a     1   March, 03 2016 00:00:00     4

我正在使用postgresql 9.6

1 个答案:

答案 0 :(得分:1)

这是解决方案:

select a.txt, count(a.txt), min(ladata)
    , (select  count(txt) from aaa b where b.txt =a.txt ) 
from aaa a  
where ladata>(select MIN(ladata) from aaa) and nall != 2  
group by txt