简体   繁体   中英

SQL SUM a column when for certain values of another 2 columns

I need to retrieve the sum of 2 columns, price and quantity.

My table has this columns:

  • id
  • doc_id
  • customer_cif
  • customer_id
  • product_code
  • quantity
  • price
  • origin

What I need is to get the sum of quantity and price for every customer_cif and product_code.

Thanks in advance.

EDIT:

This is my initial query (it gets repeated product codes and customer_cif)

SELECT id, doc_id, customer_cif, customer_id, product_code, origin,
SUM(quantity) as totQuantity, 
SUM(price) as totPrice
FROM sellings
WHERE created_at BETWEEN '2019-03-01' AND '2019-05-30'
AND (customer_cif = '01176854J' OR customer_cif = '01176862K')
GROUP BY customer_cif, product_code, doc_id

Without the doc_id I get this error:

SQL Error [1055] [42000]: Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'sellout.sci.doc_id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

try this:

select
customer_cif ,product_code,
 sum(coalesce(quantity, 0)+coalesce(price, 0) )
from your_Table
group by customer_cif ,product_code;

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