在视图SQL中过滤嵌套表

时间:2018-09-16 19:36:16

标签: sql postgresql

我正在尝试根据此查询创建视图

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

但是where data_id in (123, 345)需要自定义,因此我可以编写SELECT * from my_view where data_id in (123, 345)或使用JOIN之类的

SELECT * FROM another_table LEFT JOIN my_view ON my_view.data_id = another_table.data_id

实现此目标的最佳方法是什么?

1 个答案:

答案 0 :(得分:3)

您可以使用自定义值作为参数来创建函数:

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;

然后您可以执行以下查询:

SELECT my_function(123, 456);