我跟随查询得到错误

时间:2017-02-24 21:03:28

标签: postgresql

以下查询(使用crosstab函数到PIVOT表)会产生错误:

SELECT
  * 
FROM
 crosstab (
  'SELECT DATE_PART("year", current_date) - DATE_PART("year", i.dob) :: int age_group, 
       month :: text , count (distinct i.id):: int AS total_member 
   FROM insureds i inner join group_plans_insureds gpi on  i.id = gpi.insured_id 
   WHERE group_plan_id = 62 
       and year::text = to_char(date_trunc(''year'', current_date - ''1 month''::interval),''yyyy'')
       and DATE_PART("year", current_date) - DATE_PART("year", i.dob)) between 0 and 21'
  ) 
AS (
  code text,
  "Jan" int,
  "Feb" int,
  "Mar" int,
  "Apr" int,
  "May" int,
  "Jun" int,
  "Jul" int,
  "Aug" int,
  "Sep" int,
  "Oct" int,
  "Nov" int,
  "Dec" int
); 

产生以下错误:

  

错误:语法错误在或附近“)”LINE 6:... T(“year”,current_date) - DATE_PART(“year”,i.dob))...

1 个答案:

答案 0 :(得分:1)

您需要更改查询中的一些内容...首先,当您使用crosstab时,首先检查您要传递给它的字符串化查询总是有用的。

我认为,在你的情况下,它应该是这个:

   SELECT 
       DATE_PART('year', current_date) - DATE_PART('year', i.dob) :: int age_group, 
       month :: text , 
       count (distinct i.id) :: int AS total_member 
   FROM 
       insureds i 
       inner join group_plans_insureds gpi on  i.id = gpi.insured_id 
   WHERE 
       group_plan_id = 62 
       and year::text = to_char(date_trunc('year', current_date - '1 month'::interval),'yyyy')
       and DATE_PART('year', current_date) - DATE_PART('year', i.dob) between 0 and 21
   GROUP BY
       1, 2

作为第二步,您使用$$ --- $$分隔符引用它(因此,您不必担心将'转换为''),并将其传递给crosstab

SELECT
  * 
FROM
 crosstab (
  $$
   SELECT 
       DATE_PART('year', current_date) - DATE_PART('year', i.dob) :: int age_group, 
       month :: text , 
       count (distinct i.id) :: int AS total_member 
   FROM 
       insureds i 
       inner join group_plans_insureds gpi on  i.id = gpi.insured_id 
   WHERE 
       group_plan_id = 62 
       and year::text = to_char(date_trunc('year', current_date - '1 month'::interval),'yyyy')
       and DATE_PART('year', current_date) - DATE_PART('year', i.dob) between 0 and 21
   GROUP BY
       1, 2
   $$
  ) 
AS (
  code text,
  "Jan" int,
  "Feb" int,
  "Mar" int,
  "Apr" int,
  "May" int,
  "Jun" int,
  "Jul" int,
  "Aug" int,
  "Sep" int,
  "Oct" int,
  "Nov" int,
  "Dec" int
); 

......这应该有效。

注意:如果您需要真实的答案,请提供相关表格的定义(insuredsgroup_plans_insureds)以及一些示例数据。