简体   繁体   English

如何在PostgreSQL中添加列值?

[英]how to add column value in postgresql?

My running query is 我正在运行的查询是

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 describe in above query calculate the column Shipping_Fee_Charged , Standard_Shipping_Charges , Error and show only 10 rows. 如上述查询中所述,计算列Shipping_Fee_ChargedStandard_Shipping_ChargesError并仅显示10行。 Now i want to sum these column again, only 10 row . 现在,我想再次对这些列求和,只有10行。

How i can do this ? 我该怎么做?

You can use a subquery to store the result in a temporary table ( T1 in the code below) and from that resultset find the sum 您可以使用子查询将结果存储在临时表(下面的代码中为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

You can also use WITH Queries (Common Table Expressions) , which is similar to the above 您还可以使用上面类似的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