postgresql function 返回 select
pq函数功能很强大,我打算把统计的功能都放在数据库端。优势让运算离数据更近一些,缺点无法服用代码。牺牲了django的灵魂性,项目必须依赖postgresql。
项目中,希望实现返回select内容
后来通过bing.com查询,其实我需要的是返回表格。也是pq中的table,下面是demo
CREATE OR REPLACE FUNCTION word_frequency(_max_tokens int)
RETURNS TABLE (
txt text
,abs_cnt bigint
,relative_share numeric
) AS
$func$
BEGIN
RETURN QUERY
SELECT t.txt
,t.cnt
,round((t.cnt * 100) / (sum(t.cnt) OVER ()), 2) -- AS relative_share
FROM (
SELECT t.txt
,count(*) AS cnt
FROM token t
WHERE t.chartype = 'ALPHABETIC'
GROUP BY t.txt
ORDER BY cnt DESC
LIMIT _max_tokens
) t
ORDER BY t.cnt DESC;
END
$func$ LANGUAGE plpgsql;
简单的demo
```
CREATE or REPLACE function getselectdemo()
RETURNS TABLE (
wID NUMERIC
)
as
'
BEGIN
RETURN QUERY
select balance as wID from accounts;
end;' LANGUAGE 'plpgsql';
```