2017-02-24 60 views
-2

下面的查询(至极使用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 
); 

产生以下错误:

ERROR: syntax error at or near ")" LINE 6: ...T("year", current_date) - DATE_PART("year", i.dob)) between ...

+0

ERROR:语法错误处于或接近“)” LINE 6:... T(“year”,current_date) - DATE_PART(“year”,i.dob))... –

回答

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),以及一些示例数据的定义。

+0

谢谢,但仍然得到此错误错误:列“月”不存在 LINE 4:month :: text, ^ –

+0

其他'insureds'或'group_plans_insureds'应该包含此列。您的原始查询如何工作? – joanolo

相关问题