根据变量使用不同的子查询

时间:2018-08-27 08:30:21

标签: sql postgresql subquery

我试图根据要传递给sql的变量的值来更改表达式中使用的子查询。

我尝试了几种不同的方法,但均未成功。以下sql引发错误:子查询必须仅返回一列

WITH
sel_cells As (
    SELECT
        CASE WHEN cast (RIGHT( variable, 1 ) As int)>1 THEN (
            SELECT part_2.geom, part_2.gridcode
            FROM adm2 AS part_1, grid_1km_europe AS part_2
            WHERE part_1.gid = 7224
            AND ST_Intersects(part_1.geom, part_2.geom)
        ) ELSE (
            SELECT part_2.geom, part_2.gridcode
            FROM grid_1km_europe As part_2
            INNER JOIN grid_1km_europe_adm2 As part_1
            ON part_1.gridcode = part_2.gridcode
            WHERE part_1.adm_gid = 7224
        )
        END
),
emissions_part As (
    SELECT grid_id_1km, emissions_kg
    FROM emissions
    WHERE year_ = 2015 AND sector = 'Energy' AND pollutant = 'PM10'
)
SELECT
    a.emissions_kg,
    a.grid_id_1km,
    b.geom
FROM emissions_part As a
INNER JOIN sel_cells As b 
ON a.grid_id_1km = b.gridcode

我正在使用Postgres。

正确的方法是什么?

谢谢您的帮助!

2 个答案:

答案 0 :(得分:2)

您可以使用union all

with sel_cells As (
      select part_2.geom, part_2.gridcode
      from adm2 AS part_1 join
           grid_1km_europe as part_2
           on ST_Intersects(part_1.geom, part_2.geom)
      where part_1.gid = 7224 and
            right(variable, 1)::int > 1
      union all
      select part_2.geom, part_2.gridcode
      from grid_1km_europe As part_2 inner join
           grid_1km_europe_adm2 As part_1
           on part_1.gridcode = part_2.gridcode
      where part_1.adm_gid = 7224 and
            right(variable, 1)::int <= 1
     )

答案 1 :(得分:0)

最简单的方法是使用plpgsql。创建一个函数,该函数根据变量动态构建查询,并返回记录:

[erplndb].[dbo].[ttccom100101] b

Name    Age
Sandy   12
Amanda  14
Chris   16
Jason   11

Desired table
Name     Shoe_Size Age  Color
Sandy    8         12   Brown
Amanda   8         14   Blue
Chris    7         16   Orange
Jason    9         11   Red

然后CREATE OR REPLACE FUNCTION f1(some_var BOOLEAN) RETURNS TABLE (g INTEGER, h INTEGER) AS $BODY$ BEGIN RETURN QUERY EXECUTE 'WITH x AS (' || CASE WHEN some_var THEN 'SELECT g AS g, g AS h FROM generate_series(1, 5) g' ELSE 'SELECT g AS g, g AS h FROM generate_series(6, 10) g' END || ') SELECT g.*, x.h FROM generate_series(1, 10) g INNER JOIN x ON g.g = x.g'; END $BODY$ LANGUAGE plpgsql STABLE; 返回:

enter image description here

然后SELECT * FROM f1(TRUE)返回:

enter image description here