TSQL查找多行

时间:2015-11-14 23:36:38

标签: sql-server tsql max

在我的查询中,我需要找到每一年成本最高的供应商。

SELECT      YEAR(ORDERS.OrderDate),
            MAX(ORDERS.Freight) AS [Greatest cost]
FROM        ORDERS
GROUP BY    YEAR(ORDERS.OrderDate)
ORDER BY    YEAR(ORDERS.OrderDate) ASC

此代码确实给了我每年的最高费用,它没有给我供应商的名称。

SELECT      YEAR(ORDERS.OrderDate),
            SHIPPERS.ShipperID,
            SHIPPERS.CompanyName,
            MAX(ORDERS.Freight) AS [Greatest cost]
FROM        ORDERS, SHIPPERS
WHERE       SHIPPERS.ShipperID = ORDERS.ShipVia
GROUP BY    YEAR(ORDERS.OrderDate),
            SHIPPERS.ShipperID,
            SHIPPERS.CompanyName
ORDER BY    YEAR(ORDERS.OrderDate) ASC

这段代码给了我太多,因为它给了我每一年的所有供应商(数量最多),而我每年需要最高的供应商。

提前致谢!

2 个答案:

答案 0 :(得分:1)

有可能有几种方法可以做到这一点。这是一个:http://sqlfiddle.com/#!6/47d38/3/0

测试数据:

create table ORDERS
(
  OrderDate datetime,
  ShipVia int,
  Freight int
);

create table SHIPPERS
(
  ShipperID int,
  CompanyName nvarchar(100)
);

insert SHIPPERS values (1, 'Shipper1'), (2, 'Shipper2'), (3, 'Shipper3');

insert ORDERS values
('2011-2-1', 1, 10),
('2011-3-1', 1, 20),
('2011-2-2', 2, 5),
('2011-3-2', 2, 10),
('2011-2-3', 3, 18),
('2012-2-1', 1, 10),
('2012-3-1', 1, 20),
('2012-2-2', 2, 25),
('2012-3-2', 2, 40),
('2012-2-3', 3, 18);

查询:

with A as
(
  select
    YEAR(O.OrderDate) as [year],
    S.ShipperID,
    SUM(O.Freight) as [totalFreight]
  from ORDERS as O
  join SHIPPERS as S on O.ShipVia = S.ShipperId
  group by YEAR(O.OrderDate), S.ShipperId
)
select A.*, S.CompanyName
from A
join SHIPPERS as S on A.ShipperID = S.ShipperID
where A.totalFreight >=ALL
  (select totalFreight from A as Ainner where A.[year] = Ainner.[year]);

结果:

year    ShipperID    totalFreight    CompanyName
2011    1            30              Shipper1
2012    2            65              Shipper2

答案 1 :(得分:0)

select * from 
(
SELECT      YEAR(ORDERS.OrderDate),
            SHIPPERS.ShipperID,
            SHIPPERS.CompanyName,
            MAX(ORDERS.Freight) over (partition by YEAR(ORDERS.OrderDate), SHIPPERS.ShipperID) as max,
            row_number() over (partition by YEAR(ORDERS.OrderDate), 
                               order by ORDERS.Freight desc) as rn

FROM        ORDERS, SHIPPERS
WHERE       SHIPPERS.ShipperID = ORDERS.ShipVia 
) tt
where tt.rn = 1