按另一列值分组并计数

时间:2018-09-11 12:06:36

标签: sql postgresql aggregate greatest-n-per-group

我有一个如下表:

CREATE TABLE public.test_table
(
    "ID" serial PRIMARY KEY NOT NULL,
    "CID" integer NOT NULL,
    "SEG" integer NOT NULL,
    "DDN" character varying(3) NOT NULL
)

数据如下:

ID  CID SEG DDN
1   1   1   "711"
2   1   2   "800"
3   1   3   "124"
4   2   1   "711"
5   3   1   "711"
6   3   2   "802"
7   4   1   "799"
8   5   1   "799"
9   5   2   "804"
10  6   1   "799"

我需要按CID列对这些数据进行分组,并且获取列数取决于DDN列的第一个值,但是计数必须给我两个不同的信息(如果大于或小于1)。

很抱歉,如果无法清楚说明。让我告诉你我需要的东西。

DDN END TRA
711 1   2
799 2   1

如您所见,DDN:711具有1个单计数记录(ID:4)。这是END列。 但是2次具有多个SEG计数(ID:1to3和ID:5to6)。这是TRA列。

我不确定group子句中的哪一列!

我的解决方案:

只是找到了以下解决方案

WITH x AS (
    SELECT
        (SELECT t1."DDN" FROM public.test_table AS t1
         WHERE t1."CID"=t."CID" AND t1."SEG"=1) AS ddn,
        COUNT("CID") AS seg_count       
    FROM public.test_table AS t
    GROUP BY "CID"
)

SELECT ddn, COUNT(seg_count) AS "TOTAL",    
    SUM(CASE WHEN x.seg_count=1 THEN 1 ELSE 0 END) as "END",
    SUM(CASE WHEN x.seg_count>1 THEN 1 ELSE 0 END) as "TRA"
FROM x
GROUP BY ddn;

2 个答案:

答案 0 :(得分:2)

等效的,更快的查询:

SELECT "DDN"
     , COUNT(*) AS "TOTAL"
     , COUNT(*) FILTER (WHERE seg_count = 1) AS "END"
     , COUNT(*) FILTER (WHERE seg_count > 1) AS "TRA"
FROM  (
   SELECT DISTINCT ON ("CID")
         "DDN"          -- assuming min "SEG" is always 1
       , COUNT(*) OVER (PARTITION BY "CID") AS seg_count
   FROM   test_table
   ORDER  BY "CID", "SEG"
   ) sub
GROUP  BY "DDN";

db <>提琴here

注意:

  • CTE通常较慢,应仅在Postgres中需要的地方使用。

  • 这等效于问题假设中的查询,即每个“ CID”的最小“ SEG”始终为 1 -因为此查询返回该行带有最小“ SEG”的查询,而您的查询返回的是"SEG" = 1。通常,您希望使用“第一个”段,而我的查询会更可靠地实现此要求,但是这个问题尚不清楚。

  • COUNT(*)COUNT(column)稍快,并且等效,但不涉及NULL值(适用于此处)。相关:

  • 关于DISTINCT ON

  • 聚合FILTER语法需要Postgres 9.4 +:

答案 1 :(得分:0)

这是我提出的解决方案,我想可以简化查询。

CREATE TABLE test_table
(
    ID serial PRIMARY KEY NOT NULL,
    CID integer NOT NULL,
    SEG integer NOT NULL,
    DDN character varying(3) NOT NULL
);



insert into test_table(CID,SEG,DDN)
values
(   1,   1,   '711'),
(   1,   2,   '800'),
(   1,   3,   '124'),
(   2,   1,   '711'),
(   3,   1,   '711'),
(   3,   2,   '802'),
(   4,   1,   '799'),
(   5,   1,   '799'),
(   5,   2,   '804'),
(   6,   1,   '799');


with summary as (with ddn_t as (select cid,ddn,row_number() OVER( PARTITION BY cid)from test_table)
select a.cid,count(distinct a.ddn),b.ddn
 from ddn_t a 
 join ddn_t b on b.cid=a.cid and b.row_number=1
group by a.cid, b.ddn)
select ddn,
sum (case when count >1 then 1 else 0 end) as TRA,
sum (case when count = 1 then 1 else 0 end) as END
from summary
group by ddn;