在交叉表函数中使用case语句

时间:2017-02-22 14:53:58

标签: postgresql

是否可以在“交叉表”功能中使用case语句?这就是我迄今为止所做的。

SELECT * FROM crosstab('select distinct test_id,  cluster,total_points_earned FROM pmt_cluster')
case when test_id = 451 end AS Algebra( 
      "School___Teacher" text,
     "Analyze functions using different representations" text,
     "Construct and compare linear, quadratic, and exponential models and solve problems" text,
     "Create equations that describe numbers or relationships" text,
     "Expressions and Equations" text)
case when test_id = 454 end AS Ela( 
     "School___Teacher" text,
     "Key Ideas and Details" text,
     "Conventions of Standard English" text,
     "Craft and Structure" text,
     "Vocabulary Acquisition and Use" text)

1 个答案:

答案 0 :(得分:0)

如果我理解正确,你需要这个从psql调用它。因为在任何外部语言中创建预期的SQL语句都没有问题。

要执行此操作,您可以使用\ gset命令。它将当前查询输入缓冲区发送到服务器,并将查询的输出存储到psql变量中。 (https://www.postgresql.org/docs/current/static/app-psql.html

SELECT 451 AS test_id;
\gset


SELECT CASE WHEN :test_id = 451 THEN 'Algebra' WHEN :test_id = 454 THEN 'Ela' END AS ttype,
        '"School___Teacher"' AS f1, 'text' AS t1,
        'text' AS tX,
        CASE WHEN :test_id = 451 THEN '"Analyze functions using different representations"' WHEN :test_id = 454 THEN '"Key Ideas and Details"' END AS f2,
        CASE WHEN :test_id = 451 THEN '"Construct and compare linear, quadratic, and exponential models and solve problems"' WHEN :test_id = 454 THEN '"Conventions of Standard English"' END AS f3,
        CASE WHEN :test_id = 451 THEN '"Create equations that describe numbers or relationships"' WHEN :test_id = 454 THEN '"Craft and Structure"' END AS f4,
        CASE WHEN :test_id = 451 THEN '"Expressions and Equations"' WHEN :test_id = 454 THEN '"Vocabulary Acquisition and Use"'  END AS f5;
\gset

SELECT * 
      FROM crosstab('select distinct test_id,  cluster,total_points_earned FROM pmt_cluster')
        AS :ttype(:f1 :t1, :f2 :tX, :f3 :tX, :f4 :tX, :f5 :tX);
;