簡體   English   中英

如何在PostgreSQL中添加列值?

[英]how to add column value in postgresql?

我正在運行的查詢是

select 
to_char(fs.order_item_id ,'99999999999')as Order_Item_Id ,

(case when (sum(fs.shipping_fee) < 0) then (-sum(fs.shipping_fee))else
sum(fs.shipping_fee) END) as Shipping_Fee_Charged ,

(case when (sum(se.shipping_fee) < 0) then (-sum(se.shipping_fee)) else        
sum(se.shipping_fee) END) as Standard_Shipping_Charges , 

(case when (sum(fs.shipping_fee - se.shipping_fee) < 0) then (-
sum(fs.shipping_fee - se.shipping_fee)) else sum(fs.shipping_fee - 
se.shipping_fee) END) as Error

   from 
      "meta".fk_Payment as fs 
   join 
      "meta".ship_error as se 
   on  
     fs.order_item_id = se.order_item_id
   where
      (fs.order_status = 'delivered' and se.shipping_fee != 0 and(fs.shipping_fee-se.shipping_fee)< 0)
      and
       to_char(se.order_date, 'YYYY') = '2015'
       and
       to_char(se.order_date, 'Mon') = 'Feb' 
   group by 
  fs.order_item_id 
  limit 10;

如上述查詢中所述,計算列Shipping_Fee_ChargedStandard_Shipping_ChargesError並僅顯示10行。 現在,我想再次對這些列求和,只有10行。

我該怎么做?

您可以使用子查詢將結果存儲在臨時表(下面的代碼中為T1 )中,然后從該結果集中找到總和

SELECT SUM(T1.Shipping_Fee_Charged), SUM(T1.Standard_Shipping_Charges), SUM(T1.Error)
FROM (
  SELECT 
  to_char(fs.order_item_id ,'99999999999')as Order_Item_Id ,

  (case when (sum(fs.shipping_fee) < 0) then (-sum(fs.shipping_fee))else
  sum(fs.shipping_fee) END) as Shipping_Fee_Charged ,

  (case when (sum(se.shipping_fee) < 0) then (-sum(se.shipping_fee)) else        
  sum(se.shipping_fee) END) as Standard_Shipping_Charges , 

  (case when (sum(fs.shipping_fee - se.shipping_fee) < 0) then (-
  sum(fs.shipping_fee - se.shipping_fee)) else sum(fs.shipping_fee - 
  se.shipping_fee) END) as Error

  FROM  "meta".fk_Payment as fs 
  JOIN  "meta".ship_error as se ON  fs.order_item_id = se.order_item_id
  WHERE (fs.order_status = 'delivered' and se.shipping_fee != 0 and(fs.shipping_fee-se.shipping_fee)< 0) AND to_char(se.order_date, 'YYYY') = '2015' AND to_char(se.order_date, 'Mon') = 'Feb' 
  GROUP BY fs.order_item_id 
  LIMIT 10
) AS T1

您還可以使用上面類似的WITH Queries(公用表表達式)

WITH shipping_details AS (
         SELECT 
         to_char(fs.order_item_id ,'99999999999')as Order_Item_Id ,
       .
       .
     )
SELECT SUM(Shipping_Fee_Charged), SUM(Standard_Shipping_Charges), SUM(Error) FROM shipping_details

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM