2015-07-03 59 views
0

這樣PostgreSQL的別名數學公式

SELECT 
    brand, 
    SUM(unicom.amount_total) AS sale, 
    COUNT(sale_order.name) AS qty, 
    SUM(sale_order.amount_total)*0.15 + COUNT(sale_order_line.name)*65 + (SUM(sale_order.amount_total)*0.15 + COUNT(sale_order_line.name)*65)*0.14 
FROM 
    sale_order, 
    unicommerce 
    ...... 

我要減少複雜性在閱讀查詢,如上述。
有沒有什麼辦法可以在選擇中使用別名sale和qty?

我使用的版本9.3.6

回答

1

不幸的是你不能引用SELECT字段通過他們的別名在同一個SELECT列表中。你可以,但是,引用別名外查詢,例如:

SELECT 
    brand, 
    sale, 
    qty, 
    sale*0.15 + qty*65 + (sale*0.15 + qty*65)*0.14 
FROM (
    SELECT 
     brand, 
     SUM(unicom.amount_total) AS sale, 
     COUNT(sale_order.name) AS qty, 
    FROM 
     sale_order, 
     unicommerce 
     ...... 
); 

您也可以使用別名,在ORDER BY子句(但不WHERE,ORDER BY或HAVING)。

參見:select-lists在手冊中。

+1

雖然...可能會有性能上的影響,但是...我會檢查'EXPLAIN'以確保沒有第二次掃描正在完成。 –

0

是的,你可以用你的初始查詢作爲子查詢:

select 
    sale 
    , qty 
    , sum 
from 
(
SELECT 
    brand, 
    SUM(unicom.amount_total) AS sale, 
    COUNT(sale_order.name) AS qty, 
    SUM(sale_order.amount_total)*0.15 + COUNT(sale_order_line.name)*65 + (SUM(sale_order.amount_total)*0.15 + COUNT(sale_order_line.name)*65)*0.14 
FROM 
    sale_order, 
    unicommerce 
...) SUBQ 

或創建一個視圖和查詢視圖

0

不,你不能那樣做。但是你可以使計算用表的別名和子查詢更簡潔,但可能會導致性能下降:

SELECT 
    brand, 
    sum(u.amount_total) AS sale, 
    s.qty, 
    s.at15 + s.l_num + (s.at15 + s.l_num) * 0.14 AS big_sum 
FROM (
    SELECT count(*) AS qty, sum(amount_total)*0.15 AS at15, l.num AS l_num 
    FROM sale_order so 
    JOIN (
    SELECT sales_order, count(*) * 65 AS num 
    FROM sale_order_line 
    GROUP BY sales_order) l ON l.sales_order = s.id 
    GROUP BY name 
) s 
JOIN unicommerce u ON ...... 

一般來說,你在執行的最低水平每計算 - 例如您可以在其中訪問所有必需的列,然後分配別名並在較高級別的查詢中使用該別名。