将表原始分为Postgres中的块

时间:2016-02-27 16:30:54

标签: sql postgresql

我有一个表格,条目太长,有1和0。例如,我有表:

| Sent id.|   BoW.   |
|---------|----------|
|    1    | 10100101 |
|    2    | 00011110 |
|    3    | 10101111 |

我想创建一个新的表格来划分列BoW。将条目转换为任意长度(在本例中为4)并分配块号。

| Sent id.| Chunk No. | BoW. |
|---------|-----------|------|
|    1    |     1     | 1010 |
|    1    |     2     | 0101 |
|    2    |     1     | 0001 |
|    2    |     2     | 1110 |
|    3    |     1     | 1010 |
|    3    |     2     | 1111 |

我是初学者,试图在文档中搜索,但没有成功。也许是这样的,但具有适当的功能:

CREATE TABLE Bow2 AS
  SELECT Sent_id,
         (Chunk+1) AS Chunk_No,
         BoW/div(4) AS BoW;
  FROM Bow1;

3 个答案:

答案 0 :(得分:5)

想到的一种方法是使用public static void main(String[] args) { Category mainCat = new Category(); SubCategory m = new SubCategory(); // I want to instantiate this inside the method of class Category called createSubCategory() mainCat.setName("TITLE"); System.out.println(mainCat.getName()); // Returns --> "TITLE" THIS IS OK! mainCat.createSubcategory(m, "SUBTITLE1"); System.out.println(m.getName()); // Returns "null", I'm trying to make it return --> "SUBTITLE1" System.out.println(m.getParent());// Returns "null", I'm trying to make it return --> "mainCat (object)" }

generate_series()

此方法非常灵活,因为它适应select b.sent_id, chunk, substring(bow from (chunk - 1) * 4 + 1 for 4) from (select b.sent_id, generate_series(1, 1 + floor(length(bow) - 1 / 4) ) as chunk from bow1 b ) b; 的不同长度。

答案 1 :(得分:1)

您可以尝试这样的事情:

SELECT SentId, chunk.id, SUBSTRING(BoW FROM chunk.v FOR 4) AS BoW
FROM (VALUES (1, 1), (2, 4)) AS chunk(id, v)
CROSS JOIN mytable

查询使用包含每个块的起始位置的内联表。长度是固定的,假设它等于4.您可以调整查询以适合您的实际数据。

Demo here

答案 2 :(得分:0)

正如建议:

with recursive t(num, head, tail) as (
  select 1, substring('1234567890', 1, 3), substring('1234567890', 4)
  union all
  select num+1, substring(tail, 1, 3), substring(tail, 4) from t where tail > '')
select * from t;

 num | head |  tail   
-----+------+---------
   1 | 123  | 4567890
   2 | 456  | 7890
   3 | 789  | 0
   4 | 0    | 
(4 rows)