Reputation: 1023
I'm trying to create a view based on this query
with fields as (
select id, data_id, value
from test
where data_id in (123, 345)
),
counted as (
SELECT id, data_id, sum(meta.count) as count
FROM fields
LEFT JOIN meta ON meta.field_id = fields.id
group by data_id, meta.field_id, value
)
SELECT id, data_id, count
FROM (
SELECT id, data_id, count,
RANK() OVER (PARTITION BY data_id ORDER BY count DESC) dest_rank
FROM counted
) t
WHERE dest_rank = 1
However where data_id in (123, 345)
needs to be custom so I can write SELECT * from my_view where data_id in (123, 345)
or with a JOIN such as
SELECT * FROM another_table LEFT JOIN my_view ON my_view.data_id = another_table.data_id
What is the best way to achieve this ?
Upvotes: 1
Views: 142
Reputation: 23746
You could create a function with your custom values as parameters:
CREATE OR REPLACE FUNCTION my_function (a int, b int)
RETURNS TABLE(id int, data_id int, count int) AS $$
with fields as (
select id, data_id, value
from test
where data_id in ($1, $2)
),
...
$$ LANGUAGE SQL;
And then you could do this query:
SELECT my_function(123, 456);
Upvotes: 3