简体   繁体   中英

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. Now i want to sum these column again, only 10 row .

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

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 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM