需要从2个表中检索最大值和最小值

时间:2017-09-27 10:17:40

标签: sql

我有以下2个表格

表名:端口

City        Code
------------------
City A      001
City B      002
City C      003
City D      004
City E      005
City F      006
City G      007

表名称:货件

Code        Shipments
------------------
001         5
001         4
002         2
003         4
003         3
003         4
004         1
005         1
006         1
007         2

我希望获得最大出货量的城市列表。

答案:

City        Total Shipments
------------------------
City C      11
City D      1
City E      1
City F      1

有人可以帮我解决这个问题。

2 个答案:

答案 0 :(得分:0)

select c.city as City, sum(s.shipments) as Shipments
from 
   port c  
inner join 
    shipments s on s.code = c.code     
group by c.code
order by sum(s.shipments) asc;

检查一下并告诉我。

答案 1 :(得分:0)

您可以使用Common Table Expression(CTE)首先汇总每个城市的货件。然后可以按如下方式返回minmax记录:

WITH cte AS (   SELECT P.city AS City, 
                    SUM(S.shipments) AS TotalShipments
                FROM Port P  
                INNER JOIN Shipments S ON S.code = P.code     
                GROUP BY P.city )
SELECT *
FROM cte c
WHERE c.TotalShipments IN ( SELECT MAX(c2.TotalShipments) RequiredTotalShipments
                            FROM cte c2
                            UNION
                            SELECT MIN(c3.TotalShipments)
                            FROM cte c3 )