简体   繁体   English

我如何在PostgreSQL中执行此SQL查询

[英]how can i do this SQL query in postgreSQL

I am new to the SQL-database, I have tables and columns as follows 我是SQL数据库的新手,具有如下表和列

productInformation 产品信息

  • productInformationID(primarykey) productInformationID(主键)
  • .. ..
  • .. ..
  • price 价钱

product 产品

  • productId (primary key) productId(主键)
  • productInformationID (foreign key) productInformationID(外键)
  • ... ...
  • .. ..

soldProducts 已售产品

  • id(primarykey) id(主键)
  • productID(foreignkey) productID(外键)
  • .. ..

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? 根据此表,如何在SQL中执行此查询?

I am assuming every record in your "soldProducts" table is a single quantity. 我假设您“ soldProducts”表中的每个记录都是单个数量。 Here you go ( in postgresql ): 在这里( 在postgresql中 ):

  1. Grouped by productID to get total quantity in soldProducts, ordered by decreasing quantity and limited to highest sum (1). 按productID分组以获取所售产品的总数量,并按数量减少顺序进行排序,并限制为最高金额(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 ; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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