获取总列的比率

Getting ratio of summed columns

我有以下数据库结构。

id projectname number filename type unq count
8 prj1 2 a t1 888389f661e117 1
9 prj1 2 a t1 888389f661e117 2
10 prj1 2 a t1 888389f661e117 2
11 prj1 2 a t2 816418549711c3d33 6
12 prj1 2 a t2 816418549711c3d33 7
13 prj1 2 a t2 816418549711c3d33 1
14 prj1 2 a t3 NULL NULL
15 prj1 2 a t3 NULL NULL
16 prj1 2 a t3 NULL NULL
17 prj1 36 b t1 8dac5bdffc7f86502 0
18 prj1 36 b t1 8dac5bdffc7f86502 0
19 prj1 36 b t1 8dac5bdffc7f86502 0

我使用下面的查询来获取 count 列 w.r.t 的总和。 type 列。一行的唯一标识符是`(projectname, number, filename).

SELECT DISTINCT ON (projectname, number, type) number, type, SUM(count) as count
FROM myTable
GROUP BY (projectname, number, type)
ORDER BY number

这给了我输出

number type count
2 t1 5
2 t2 14
2 t3 NULL
36 t1 0
36 t2 16
36 t3 NULL

我的理想输出是:对于每个 number 列项目,我想将 t2 值除以 t1 并将 t3 值除以 t2.我可以在不使用外部数据操作技术的情况下使用 Postgres 命令完成此操作吗?我希望获得如下所示的 table。 type 列只是代表我感兴趣的操作。

number type ratio
2 t2t1 14 by 5
2 t3t2 NULL by 14 is NULL
36 t2t1 16 by 0 is INF
36 t3t2 NULL by 16 is NULL

根据您的 which gives me the output 我们可以尝试使用 LEADROW_NUMBER window 函数来获取下一个 count 并过滤每个 number

SELECT number,
       type,
       CASE WHEN count = 0 THEN 'INF' ELSE (n_count::DECIMAL(8,3) /count )::VARCHAR(20) END
FROM (
  SELECT *,
        LEAD(count) OVER(PARTITION BY number ORDER BY type) n_count,
        ROW_NUMBER() OVER(PARTITION BY number ORDER BY type DESC) rn 
  FROM (
    SELECT DISTINCT ON (projectname, number, type) number, type, SUM(count) as count
    FROM myTable
    GROUP BY (projectname, number, type)
    ORDER BY number
  ) t1
) t1
WHERE rn > 1

但我看到了完整的示例数据并期望您可能需要使用基于 typenumberOUTER JOIN 的结果,它是由 CROSS JOIN[=22= 创建的]

WITH CTE AS (
 SELECT *
 FROM (
  SELECT distinct type
  FROM myTable
 ) t1 CROSS JOIN (
  SELECT distinct number
  FROM myTable
 ) t2
)
SELECT number,
       type,
        CASE WHEN count = 0 THEN 'INF' ELSE (n_count::DECIMAL(8,3) /count )::VARCHAR(20) END
FROM (
  SELECT *,
        LEAD(count) OVER(PARTITION BY number ORDER BY type) n_count,
        ROW_NUMBER() OVER(PARTITION BY number ORDER BY type DESC) rn 
  FROM (
    SELECT t1.number, t1.type, SUM(t2.count) count
    FROM CTE t1
    LEFT JOIN myTable t2
    ON t1.type = t2.type
    AND t1.number = t2.number
   GROUP BY t1.number, t1.type
  ) t1
) t1
WHERE rn > 1

sqlfiddle