I wonder is there a way to shorten below SELECT CASE query, by replacing the repeating arithmetic ((table1.col_a + table2.col_b) / 2) with something like a variable?
SELECT
CASE
WHEN ((table1.col_a + table2.col_b) / 2) < 100 THEN 1
WHEN ((table1.col_a + table2.col_b) / 2) < 200 THEN 2
WHEN ((table1.col_a + table2.col_b) / 2) < 250 THEN 3
WHEN ((table1.col_a + table2.col_b) / 2) < 300 THEN 4
WHEN ((table1.col_a + table2.col_b) / 2) < 800 THEN 5
<... till 20>
END bucket_range
COUNT(table1.id) as stats
FROM
table1 INNER JOIN table2
ON table1.column_x = table2.column_y
WHERE
<filter conditions>
GROUP BY 1
ORDER BY bucket_range
The solution has to be single SELECT query (on PostgreSQL 10), not stored procedure or function. It should not impact performance.
I tried the following but they are invalid:
SELECT
CASE ((table1.col_a + table2.col_b) / 2)
WHEN < 100 THEN 1
WHEN < 200 THEN 2
and
SELECT
CASE ((table1.col_a + table2.col_b) / 2) AS x
WHEN x < 100 THEN 1
WHEN x < 200 THEN 2
--- Update note
The comparison evaluation arithmetic < bound_number THEN 1 was just a simplified example. The actual bucket sizes are not consistent, I just updated the question to clarify this. The idea is that the arithmetic expression is repeating across cases.
where (table1.col_a + table2.col_b) / 2 between begin_col and end_col.WHEN same_expr < 100*N THEN N, then you could use just pure math withoutcaseat all :)cross apply (select count(*) + 1 from (values (100), (200), (250), (300), (800)) t(v) where v < (table1.col_a + table2.col_b) / 2) as t2(bucket_range)Not sure it's a huge improvement.substring(' 1 234 5', table1.col_a + table2.col_b) / 2 / 50, 1)