使用参数调用函数或视图

时间:2015-05-13 09:42:06

标签: sql windows postgresql

我想创建一个功能或视图,它会显示特定年份的某些信息。

CREATE OR REPLACE VIEW name_view AS 
    SELECT d_name,
    SUM("Jan") "Jan",
    SUM("Feb") "Feb"
    ...
    FROM (
    select distinct d_name,
      COUNT(CASE WHEN EXTRACT (MONTH FROM h_date) = '01' THEN query_string ELSE NULL END) "Jan",
      COUNT(CASE WHEN EXTRACT (MONTH FROM h_date) = '02' THEN query_string ELSE NULL END) "Feb",
    ..
       from h
           inner join d on h_d = d_id
                WHERE EXTRACT (YEAR FROM h_date) = '2015' 
            GROUP BY  d_name) sub query
    GROUP BY d_name

如何在没有

的情况下调用此类视图
  

提取的地方(年份来自h_date)='2015'

但随着通话年份的到来?例如

  

SELECT * FROM name_view('2015')

2 个答案:

答案 0 :(得分:1)

您应该在SELECT中使用YEAR,当您从视图中选择时,使用WHERE year = 2015.

CREATE OR REPLACE VIEW name_view AS 
SELECT d_name,
SUM("Jan") "Jan",
SUM("Feb") "Feb",
YEAR,
....

使用视图:

SELECT * 
FROM name_view 
WHERE year = '2015';

答案 1 :(得分:1)

您可以尝试将此功能作为参数传递日期:

CREATE OR REPLACE FUNCTION "show_info"("DATE" date)
  RETURNS SETOF show_info AS
$BODY$SELECT d_name,
    SUM("Jan") "Jan",
    SUM("Feb") "Feb"
    ...
    FROM (
    select distinct d_name,
      COUNT(CASE WHEN EXTRACT (MONTH FROM h_date) = '01' THEN query_string ELSE NULL END) "Jan",
      COUNT(CASE WHEN EXTRACT (MONTH FROM h_date) = '02' THEN query_string ELSE NULL END) "Feb",
    ..
       from h
           inner join d on h_d = d_id
                WHERE EXTRACT (YEAR FROM h_date) = $1 
            GROUP BY  d_name) subquery
    GROUP BY d_name
;$BODY$
  LANGUAGE sql VOLATILE
  COST 100
  ROWS 1000;

您可以将其称为

select * from show_info(date)

此处的日期将是您想要传递的日期