2017-02-22 42 views
2

是否可以在「crosstab」函數中使用case語句?這是我迄今爲止所做的。在交叉表函數中使用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) 

回答

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); 
; 
+0

出現以下錯誤:錯誤:您沒有運行GSET查詢的權限。我認爲這將工作,如果我可以通過此權限錯誤。 – Joe

+0

第一次gset或第二次出現此錯誤? –

+0

它是第一個gset。 – Joe