简体   繁体   English

将两个不同表中的两列相乘后求最大值 - SQL

[英]Find maximum after multiplying two columns from two different tables - SQL

I'm trying to find the right way to find the maximum after multiplying 2 columns in different tables: Orders (OID, PID, Quantity, Date) Products (PID, Pname, Price, Category, Subcategory) .我试图找到在不同表中乘以 2 列后找到最大值的正确方法: Orders (OID, PID, Quantity, Date) Products (PID, Pname, Price, Category, Subcategory) I need to find which OID has the highest total order amount.我需要找到哪个 OID 的总订单金额最高。 I've tried this:我试过这个:

SELECT OID, OrderAmount
FROM Orders
WHERE OrderAmount=(SELECT MAX(OrderAmount) from Orders
(SELECT Orders.OID, OrderAmount=Products.Price*Orders.Quantity
FROM Orders
INNER JOIN Products ON Orders.PID=Products.PID); 

Maybe there is a more effective solution?也许有更有效的解决方案? Thanks all in advance!提前谢谢大家!

Method 1: Aggregate function方法一: Aggregate函数

SELECT TOP 1 OID, MAX(OrderAmount) MaxOrderAmount
FROM (
       SELECT Orders.OID, OrderAmount = Products.Price * Orders.Quantity
       FROM Orders INNER JOIN Products ON Orders.PID=Products.PID
     ) X GROUP BY OID

Method 1: Row_Number Concept方法一: Row_Number概念

SELECT TOP 1 OID, OrderAmount AS MaxOrderAmount
FROM (
       SELECT Orders.OID, OrderAmount = Products.Price * Orders.Quantity
              ROW_NUMBER() OVER(ORDER BY Products.Price * Orders.Quantity) RN
       FROM Orders INNER JOIN Products ON Orders.PID=Products.PID
     ) X WHERE RN = 1

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

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