【问题标题】:How to make view to show from 2 tables as 1 table with rows as columns如何使视图从 2 个表显示为 1 个表,以行为列
【发布时间】:2018-05-23 04:28:31
【问题描述】:

我有 2 张桌子:

CREATE TABLE public.objects
(
  id bigint NOT NULL DEFAULT nextval('objects_id_seq'::regclass),
  value text,
  CONSTRAINT objects_pkey PRIMARY KEY (id)
);
CREATE TABLE public.relation
(
  id1 bigint,
  id2 bigint,
  multiplier integer
);

objects 表存储关于任何对象的数据,relation 表通过它们的 id 存储对象之间的关系,multiplier 是关于关系的数据。

请帮助提出将其显示为简单表格的请求,其中对象为列和行,乘数为关系值(列和行)

这样

Comps 和 Products 作为对象,值作为乘数。

【问题讨论】:

  • 请同时添加一些示例值。
  • @FahadAnjum 请。我将样本添加为 2 张图片。
  • 可以在postgres中查看crosstab功能。

标签: sql postgresql pivot crosstab


【解决方案1】:

@Fahad Anjumthanx....

SELECT * FROM crosstab('select o.value, o1.value, r.multiplier::text FROM objects as o, objects as o1, relation as r 
    where 
        o.id=r.id1 and
        o1.id = r.id2')
    AS ct(com text, P1 text, P2 text, P3 text);

这是工作......

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多