所以我想找到每个员工的最小/最大值以及这些订单的一些细节(现在只说订单日期),除了我得到的是一堆错误值的重复行
select EMP.SaleID,EMP.Name, MinOrder.OrderDate, min(MinOrder.OrderTotal) , [MinOrder.Otherdetails], MaxOrder.OrderDate, Max(MaxOrder.OrderTotal) ,[MaxOrder.Otherdetails]
from Employees as EMP
inner join Orders as MinOrder on MinOrder.SaleID = EMP.SaleID
inner join Orders as MaxOrder on MaxOrder.SaleID = EMP.SaleID
group by Sales.Account, MinOrder.OrderDate, MaxOrder.OrderDate, [MinOrder.Otherdetails],[MaxOrder.Otherdetails]
员工表:
SaleID Name etc
1 Jim
2 Bob
订单表:
OrderID SaleID OrderDate OrderTotal [OtherDetails]
1 1 1/1/14 1000 ...
2 1 2/2/13 2000 ...
3 1 1/3/13 3000 ...
4 2 2/2/12 1000 ...
我想要的是
SaleID Name MinOrderDate MinOrderTotal MaxOrderDate MaxOrderTotal OtherMax/Mindetails
1 Jim 1/1/14 1000 1/3/13 3000 ...
2 Bob 2/2/12 1000 2/2/12 1000 ...
答案 0 :(得分:1)
也许不是最直接的方法,但您可以使用公用表表达式对行进行排名,使用普通联接来获取最小/最大行的数据;
WITH cte AS (
SELECT e.saleid, name, orderid, orderdate, ordertotal,
ROW_NUMBER() OVER (PARTITION BY name ORDER BY ordertotal) rn1,
ROW_NUMBER() OVER (PARTITION BY name ORDER BY ordertotal DESC) rn2
FROM employees e JOIN orders o
ON e.saleid = o.saleid
)
SELECT c1.saleid, c1.name,
c1.orderdate minorderdate, c1.ordertotal minordertotal,
c2.orderdate maxorderdate, c2.ordertotal maxordertotal
FROM cte c1
JOIN cte c2
ON c1.saleid=c2.saleid
WHERE c1.rn1=1 AND c2.rn2=1
ORDER BY saleid;