简体   繁体   中英

how can i do this SQL query in postgreSQL

I am new to the SQL-database, I have tables and columns as follows

productInformation

  • productInformationID(primarykey)
  • ..
  • ..
  • price

product

  • productId (primary key)
  • productInformationID (foreign key)
  • ...
  • ..

soldProducts

  • id(primarykey)
  • productID(foreignkey)
  • ..

I am trying to find the sold product with the highest quantity and the total price of this sale.

According to this tables, how can I do this query in SQL?

I am assuming every record in your "soldProducts" table is a single quantity. Here you go ( in postgresql ):

  1. Grouped by productID to get total quantity in soldProducts, ordered by decreasing quantity and limited to highest sum (1).
  2. Select the products having highest total quantity

  3. Then, a series of two joins to get to price to calculate total sale.

     SELECT max.productID, max.total_quant , p.price*max.total_quant AS total_sale FROM (SELECT productID, COUNT(*) as total_quant FROM soldProducts GROUP BY productID HAVING COUNT(*) = (SELECT COUNT(*) as total_quant FROM soldProducts GROUP BY productID ORDER BY total_quant DESC LIMIT 1)) as max JOIN products AS p ON max.productID = p.productid JOIN productInformation AS pi ON p.productInformationID = pi.productInformationID ; 

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