2

我有 2 个表 Sales & Purchase,带有字段 SaleId、Rate、Quantity、Date、CompanyId、UserID 的 Sales 表。包含字段 PurchaseId、Rate、Quantity、Date、CompanyId、UserID 的采购表。

我想从任一表中选择一个具有最高 Rate*Quantity 的记录。

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
4

3 回答 3

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
于 2013-06-29T09:48:38.857 回答
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
于 2013-06-29T09:49:39.033 回答
0

你可以做

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

或者

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

您还可以考虑是否有两个相等的“最大”记录。(第二个选项将返回两者,第一个只是一个 - 随机)

于 2013-06-29T09:44:59.583 回答