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

时间:2019-01-29 16:25:43

标签: clickhouse

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

我需要在表test.test上绑定MATERIALIZED VIEW,以聚合记录WHERE idx = 1并将新记录以不同的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 │
└─────┴─────┘

1 个答案:

答案 0 :(得分:1)

尝试此查询(只是考虑到求和将应用于插入的数据包,而不是表 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 表引擎:

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;