我有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
答案 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)
您可以使用MAX
和UNION 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