简体   繁体   English

如何通过选择查询将 SQL 表长度添加为列?

[英]How to add SQL table length as a column through select query?

Context: I want to add an extra column in my table which specifies the length of the table.上下文:我想在我的表中添加一个额外的列,指定表的长度。 This will be used by me when I union multiple charts - knowing the length of the original chart will be used in a computation function (which I'll do in a UDF python function).当我合并多个图表时,我将使用它 - 知道原始图表的长度将用于计算函数(我将在 UDF python 函数中执行)。

Question: how can I add the length of the table as a column to my view.问题:如何将表格的长度作为一列添加到我的视图中。 Currently, my columns look like this:目前,我的专栏如下所示:

Primary key | attr1 | attr2 | attr3 | attr4

I want them to look like this:我希望它们看起来像这样:

Primary key | attr1 | attr2 | attr3 | attr4 | len_table

I tried using count(*) then joining the table but obviously that didn't work as count returns an integer and there's no attribute to join "on"我尝试使用count(*)然后加入表,但显然这不起作用,因为 count 返回一个整数并且没有加入“on”的属性

CREATE temp TABLE source (
    col1 int,
    col2 int,
    col3 text
);

INSERT INTO source
SELECT
    i,
    i + 1,
    'i=' || i || 'i+1 = ' || i + 1
FROM
    generate_series(1, 4) g (i);

CREATE OR REPLACE VIEW myview AS
SELECT
    col1,
    col2,
    col3,
    'hello' AS col4,
    count(*) OVER (ORDER BY col1) AS col5
FROM
    source
WHERE
    col1 < 4;

TABLE myview;

UPDATE
    myview
SET
    col1 = 3
WHERE
    col1 = 2
RETURNING
    *;

Hope this work for you.希望这对你有用。 Since you have count aggregate function then you cannot directly update this view.由于您具有计数聚合功能,因此您无法直接更新此视图。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM