78

postgres で計算列を使用する際に問題が発生しています。SQL で動作する同様のコードを以下に示します。これを で再作成することは可能PostgreSQLですか?

select cost_1, quantity_1, cost_2, quantity_2, 
      (cost_1 * quantity_1) as total_1,
      (cost_2 * quantity_2) as total_2,
      (calculated total_1 + calculated total_2) as total_3
from data;

PostgreSQL同様のコードでは、次のエラーが返されます。

列 total_1 および total_2 は存在しません。

4

5 に答える 5

68

列エイリアスにアクセスできるようにするには、SELECT ステートメントを派生テーブルにラップする必要があります。

select cost1,
       quantity_1,
       cost_2,
       quantity_2
       total_1 + total_2 as total_3
from (
    select cost_1, 
           quantity_1, 
           cost_2, 
           quantity_2, 
           (cost_1 * quantity_1) as total_1,
           (cost_2 * quantity_2) as total_2
    from data
) t

その上でパフォーマンスが低下することはありません。

(元の SQL ステートメントが DBMS でまったく実行されることに本当に驚いています)

于 2012-01-12T20:35:40.357 に答える
52

クエリ全体をouterqueryでラップしたくない場合は、次を使用LATERALして中間total_1とを計算できtotal_2ます。

SELECT cost_1, quantity_1, cost_2, quantity_2, total_1, total_2,
       total_1 + total_2 AS total_3
FROM data
,LATERAL(SELECT cost_1 * quantity_1, cost_2 * quantity_2) AS s1(total_1,total_2);

DBFiddle デモ

出力:

╔═════════╦═════════════╦═════════╦═════════════╦══════════╦══════════╦═════════╗
║ cost_1  ║ quantity_1  ║ cost_2  ║ quantity_2  ║ total_1  ║ total_2  ║ total_3 ║
╠═════════╬═════════════╬═════════╬═════════════╬══════════╬══════════╬═════════╣
║      1  ║          2  ║      3  ║          4  ║       2  ║      12  ║      14 ║
║      3  ║          5  ║      7  ║          9  ║      15  ║      63  ║      78 ║
║     10  ║          5  ║     20  ║          2  ║      50  ║      40  ║      90 ║
╚═════════╩═════════════╩═════════╩═════════════╩══════════╩══════════╩═════════╝
于 2016-04-10T13:13:28.230 に答える
-4

式で列エイリアスを使用しようとしています。システムがそれを可能にする場合、それは単なるシンタックス シュガーです。これは、どの SQL ダイアレクトでも機能するはずです。

select 
 cost_1
,quantity_1
,cost_2
,quantity_2
,cost_1 * quantity_1 as total_1
,cost_2 * quantity_2 as total_2
,(cost_1 * quantity_1) + (cost_2 * quantity_2) as total_3 

from data;
于 2012-01-12T18:33:40.740 に答える