我有一个订单表(简化)
OrderId,
SalesPersonId,
SaleAmount,
CurrencyId,
...
我正在尝试在此表上创建一个报告,我希望有类似的内容:
SalesPersonId TotalCAD TotalUSD
1 12,345.00 6,789.00
2 7,890.00 1,234.00
我不想做自我加入(也许我过早地进行优化,但这似乎效率低下)IE:
SELECT SalesPersonId, SUM(OrdersCAD.SaleAmount), SUM(OrderUSD.SaleAmount)
FROM Orders
LEFT JOIN Orders AS OrdersCAD ON Orders.OrderID AND Orders.CurrencyID = 1
LEFT JOIN Orders AS OrdersUSD ON Orders.OrderID AND Orders.CurrencyID = 2
但我想不出另一种方法可以做到这一点,任何想法?
答案 0 :(得分:8)
使用CASE块:
SELECT
SalesPersonId,
SUM(
CASE CurrencyID
WHEN 1 THEN SaleAmount
ELSE 0
END
) AS TotalCAD,
SUM(
CASE CurrencyID
WHEN 2 THEN SaleAmount
ELSE 0
END
) AS TotalUSD
FROM Orders
GROUP BY SalesPersonId
答案 1 :(得分:2)
试试这个:
SELECT SalesPersonId,
SUM(CASE WHEN CurrencyID = 1 THEN SaleAmount ELSE 0 END) as CAD,
SUM(CASE WHEN CurrencyID = 2 THEN SaleAmount ELSE 0 END) as USD
FROM ORDERS
答案 2 :(得分:0)
考虑尝试一个标量值函数(SQL Server 2000或更高版本)。
CREATE FUNCTION dbo.GetOrdersSumByCurrency
(
@SalesPersonID INT, @CurrencyID INT
)
RETURNS DECIMAL(10, 2)
AS
BEGIN
DECLARE @Sum DECIMAL(10, 2)
SELECT @Sum = ISNULL(SUM(SalesAmount), 0) FROM dbo.Orders
WHERE SalespersonID=@SalesPersonID AND CurrencyID = @CurrencyID
RETURN @Sum
END
然后执行此类SQL以获取结果(假设您还有一个单独的salespersons表,或者使用SELECT DISTINCT SalesPersonId .... FROM Orders):
SELECT SalesPersonId,
dbo.GetOrdersSumByCurrency(SalesPersonId, 1) AS SumUSD, dbo.GetOrdersSumByCurrency(SalesPersonId, 2) AS SumCAD
FROM SalesPersons
确保运行查询计划,以查看它是否与您需要的功能相比,与此处建议的其他可能性进行比较,尤其是在处理大量数据时。