使用PostgresSQL 9.3,OSX。
我已经将以下功能混为一谈 令人震惊的是,它可以工作并根据位置返回单个邮政编码列表。
我现在想要/循环遍历那些运行select查询的结果,每个邮政编码返回一个多列表。将以下SELECT查询合并到此函数中的最佳方法是什么?
SELECT "NPI" FROM doc
WHERE "Provider Business Mailing Address Postal Code"='<ZIPCODERESULTS FROM BELOW>';
CREATE FUNCTION get_npizips (text) RETURNS TABLE(a char(5)) AS '
DECLARE
-- Declare aliases for user input.
npi_id ALIAS FOR $1;
-- Declare a variable to hold the zipcode
zipcode varchar;
BEGIN
SELECT INTO zipcode substring(provider_nodes.address_postal_code for 5) FROM provider_nodes
WHERE provider_nodes.npi = npi_id;
RETURN QUERY SELECT zcta FROM zctas WHERE ST_DWithin(
geom,
(
SELECT geom
FROM zctas
WHERE zcta = zipcode
),
7 * 1.6 * 1000
);
END;
'LANGUAGE 'plpgsql';
答案 0 :(得分:0)
所有 归结为此简化查询:
SELECT d."NPI"
FROM provider_nodes p
JOIN zctas z0 ON z0.zcta = left(p.address_postal_code, 5)
JOIN zctas z ON ST_DWithin(z.geom, z0.geom, 7 * 1.6 * 1000)
JOIN doc d ON "Provider Business Mailing Address Postal Code" = z.zcta
WHERE p.npi = <your npi_id here>;
您的功能有多个缺点。 如果你想要另外保留它,我建议:
CREATE FUNCTION get_npizips (npi_id text)
RETURNS SETOF text AS
$func$
SELECT z.zcta
FROM provider_nodes p
JOIN zctas z0 ON z0.zcta = left(p.address_postal_code, 5)
JOIN zctas z ON ST_DWithin(z.geom, z0.geom, 7 * 1.6 * 1000)
WHERE p.npi = $1
$func$ LANGUAGE sql;
plpgsql
。