我有下面的数据库 struct .

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命令来实现这一点吗?我希望获得如下表格.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,我们可以try 使用LEADROW_NUMBER窗口函数来获得下一个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

但我看到了完整的样本数据和预期结果,您可能需要使用OUTER JOIN,基于CROSS JOIN创建的typenumber

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

Database相关问答推荐

Symfony2:spl_object_hash() expects parameter 1 to be object, string given in Doctrine

使用 SQLAlchemy Core 批量插入列表值

哪个本地数据库适合 Windows 8 应用store 应用?

MongoDB:查询具有两个相等字段 $match 和 $eq 的文档

在一次 SQL 查询中更新多行的多列

在迁移中添加行

每个请求可以多次查询 MongoDB 吗?

单向和双向关系关系的区别

什么是 Scalar标量查询?

ODBC 与 JDBC 与 ADO.NET

FOR UPDATE和JOIN的 SQL 语义

用于获取存储在单个表中的 n 级父子关系的 Postgresql 查询

Neo4j:逐步创建自动索引

HTML5 数据库存储 (SQL lite) - 几个问题

friendship数据库模式

MySQL:LAST_INSERT_ID() 返回 0

从原始物理文件中恢复 postgreSQL 数据库

SQL 查询 - 如何按 null 或不为 null 进行过滤

如何修复 Postgres 上过时的 postmaster.pid 文件?

Cassandra - 事务支持