通过连接两个表来选择具有最高金额的记录

时间:2013-06-29 09:30:13

标签: sql sql-server sql-server-2008

我有2张桌子销售&购买,销售表格,字段为SaleId,Rate,Quantity,Date,CompanyId,UserID。购买表包含字段PurchaseId,Rate,Quantity,Date,CompanyId,UserID。

我想从任一表中选择具有最高费率*数量的记录。

SELECT SalesId Or PurchaseId FROM Sales,Purchase 
where Sales.UserId=Purchase.UserId and Sales.CompanyId=Purchase.CompanyId 
AND Sales.Date=Current date 
AND Purchase.Date=Current date AND Sales.UserId=1 
AND Purchase.UserId=1 AND Sales.CompanyId=1 AND Purchase.ComoanyId=1

3 个答案:

答案 0 :(得分:1)

尝试:

select top 1 * from
(select SalesId ID, Rate, Quantity, 'Sales' TransactionType
 from sales
 union all
 select PurchaseId ID, Rate, Quantity, 'Purchase' TransactionType
 from purchase)
order by Rate * Quantity desc

答案 1 :(得分:0)

你可以做到

SELECT TOP 1 * FROM ... ORDER BY Rate * Quantity DESC

SELECT ... WHERE Rate * Quantity = (SELECT max(Rate * Quantity) FROM ... )

你也可以考虑是否有两个相同的' max'记录。 (第二个选项将返回两个,第一个只返回一个 - 随机)

答案 2 :(得分:0)

您可以使用MAXUNION ALL

SELECT MAX(RateQty) FROM
( SELECT Rate*Quantity as RateQty
  FROM Sales
  WHERE Sales.UserId=1 AND Sales.CompanyId=1 AND Sales.Date = GETDATE()
  UNION ALL
  SELEC Rate*Quantity as RateQty
  FROM Purchase
  WHERE Purchase.UserId=1 AND Purchase.CompanyId=1 AND  Purchase.Date= GETDATE()
) SalesPurchase