ClickHouse:从 select 访问具有相同列名的源列

ClickHouse: access to the source column from select with the same column name

当我在 SELECT 块中有相同的列名时,我无法访问 WHERE 块中的源列值。

我需要在 table test.test 上绑定 MATERIALIZED VIEW,它聚合记录 WHERE idx = 1 并将新记录推送到相同的 table test.test,但具有不同的 idx值。

create table test.test (
    idx UInt8,
    val Int64
) engine Memory()
insert into test.test (idx, val)
values 
    (toUInt8(1), toInt64(1)),
    (toUInt8(1), toInt64(2)),
    (toUInt8(1), toInt64(3))
-- Not working
select 2 as idx, sum(val) as val
from test.test
where idx = 1
-- Working fine, but not allowed with materialized view
select _idx as idx, val
from (

    select 2 as _idx, sum(val) as val
    from test.test as t
    where t.idx = 1

)

预计

┌─idx─┬─val─┐
│   2 │   6 │
└─────┴─────┘

实际

┌─idx─┬─val─┐
│   2 │   0 │
└─────┴─────┘

试试这个查询(只要考虑到求和将应用于插入数据包,而不是 table test.test 中的所有行. 换句话说,视图将包含不止一行 idx==2) :

CREATE MATERIALIZED VIEW test.test_mv TO test.test AS
SELECT
    toUInt8(2) AS idx,
    val
FROM
(
    SELECT sum(val) AS val
    FROM test.test
    WHERE idx = 1
)

我建议使用更适合您情况的 SummingMergeTree table 引擎:

CREATE MATERIALIZED VIEW IF NOT EXISTS test.test_mv2
ENGINE = SummingMergeTree
PARTITION BY idx
ORDER BY idx AS
SELECT
    idx,
    sumState(val) as sum
FROM test.test
GROUP BY idx;



SELECT
    idx,
    sumMerge(sum)
FROM test.test_mv2
GROUP BY idx;