sql - 在 View sql中过滤嵌套表

标签 sql postgresql

我正在尝试基于此查询创建 View

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

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

最佳答案

您可以创建一个将您的自定义值作为参数的函数:

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);

关于sql - 在 View sql中过滤嵌套表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52357746/

相关文章:

mysql - 优化 5 表 SQL 查询(stores => items => words)

使用 WAMP 在浏览器中显示为注释的 PHP 代码

sql - 计算某一列中另一列的值为 1 的行数

c# - 如何在 PostgreSQL 中存储 DateTimeOffset

Google Cloud Run 中的 Django 找不到/云 sql 套接字

php - PostGIS 中的聚类点

sql - 仅当 subselect 不为 null 时才插入值

sql - oracle sqlplus中的多行注释

mysql - 如何确定数据库服务器或嵌入式数据库是否合适

java - 准备好的语句有不同数量的 where 子句