Postgres query convert to clickhouse with conditional count

270 Views Asked by At

I need to convert this postgres query to clickhouse:

select count(1) filter (where car_model = 'chevrolet'), count(distinct car_num) filter (where car_model='chevrolet') from cars;

I have tried with countIf, but it does not accept the condition. so I need an option.

1

There are 1 best solutions below

0
JustMe On

What do you mean by it does not accept the condition?

It works as expected:

CREATE TABLE cars
(
    `car_model` String,
    `car_num` integer
)
ENGINE = MergeTree
ORDER BY tuple();

insert into cars values ('chevrolet', 1),  ('chevrolet', 1), ('opel', 2), ('chevrolet', 3), ('dodge', 4), ('subaru', 16);

Query:

SELECT
    countIf(1, car_model = 'chevrolet'),
    countIfDistinct(car_num, car_model = 'chevrolet')
FROM cars

Result:

Row 1:
──────
countIf(1, equals(car_model, 'chevrolet')):           3
uniqExactIf(car_num, equals(car_model, 'chevrolet')): 2

1 row in set. Elapsed: 0.024 sec.