登录
首页 >  Golang >  Go问答

PSQL 查询根据条件创建多个选择查询以过滤掉值

来源:stackoverflow

时间:2024-03-16 14:18:29 338浏览 收藏

本查询旨在根据表 final 中的 inp 列值创建多个选择查询。当 inp 为 1 时,查询将返回唯一 gid 和 gname,按 gname 排序;当 inp 为 2 时,将返回唯一 pid 和 pname,其中 gid 与指定值匹配,按 pname 排序;当 inp 为 3 时,将返回唯一 did 和 name,其中 pid 与指定值匹配,按 name 排序。该查询利用案例语句实现此逻辑,根据 inp 的值选择要返回的列。最终结果按返回的名称值排序。

问题内容

with final as (
    select 'a' as gname, 'b' as pname, 'c' as name, 1 as gid, 2 as pid, 3 as did, 3 as inp
    union
    select 'a1' as gname, 'b1' as pname, 'c1' as name, 11 as gid, 21 as pid, 31 as did, 3 as inp
)

现在我想根据 inp 列值编写一个查询

select 
    (case final.inp 
    when 1
        then 
        (select distinct(final.gid) as id, final.gname as name from
        final order by final.gname)
    when 2
        then 
        (select distinct(final.pid) as id, final.pname as name from
        final where final.gid = $1 order by final.pname)
    when 3 
        then 
        (select distinct(final.did) as id, final.name as name from
        final where final.pid = $1 order by final.name)

    end)
        from (%s) final;

我知道这不是正确的书写方式。

但这会让您了解我正在尝试做什么。

如果 inp = 1 -> 获取唯一的 gid 和 gname 并按 gname 排序

如果 inp = 2 -> 获取唯一的 pid 和 pname,其中 gid = 并按 pname 排序。

我想在psql中编写这个逻辑。

我知道案例 只能有一列时,因此我必须为单个 final.inp=1 的名称和 id 创建两个案例。

由于这部​​分,我无法编写这个逻辑

(SELECT DISTINCT(final.pid) AS id, final.pname as name FROM
final WHERE final.gid = $1 ORDER BY final.pname)

where order by <--- 并将相同的最终值传递给它。 我无法实施它。有人可以帮忙吗?


正确答案


仅假设

select distinct 
case when inp = 1 then gid
       when inp = 2 then pid
       when inp = 3 then did
  end new_id,
  case when inp = 1 then gname
       when inp = 2 then pname
       when inp = 3 then name
  end as name
from final
order by 2

DB Fiddle playground

本篇关于《PSQL 查询根据条件创建多个选择查询以过滤掉值》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>