SQL查询汇总子表的结果

时间:2019-07-26 07:03:59

标签: sql-server

我需要连接4个表并在我的应用程序中显示记录

route1
-------------------------
| ID | MODE | SCH DATE   | 
| 1  | T    | 1/12019    |  
| 2  | T    | 2/12019    |  
| 3  | T    | 2/12019    |
--------------------------

Stop2
----------------------------
| ID | routeID | LocationID | 
| 1  |    1    |     1      |  
| 2  |    1    |     2      |  
| 3  |    1    |     3      | 
| 4  |    2    |     4      |  
| 5  |    2    |     5      |  
| 6  |    3    |     6      |  
-----------------------------

StopOrder2
----------------------------
| ID |  StopID |   Wight    | 
| 1  |    1    |     100    |  
| 2  |    1    |     2      |  
| 3  |    2    |     3      | 
| 4  |    2    |     1      |  
| 5  |    3    |     2      |  
| 6  |    3    |     3      |  
| 7  |    4    |     2      |  
| 8  |    4    |     3      |  
| 9  |    5    |     2      |  
| 10 |    5    |     3      |  
| 11 |    6    |     2      |  
| 12 |    6    |     3      |
-----------------------------

位置


|  LocationID |  Name, City, Zip
|      1      |  name1,city1 1111
|      2      |   name2,city2 2222
|      3      | name3,city3 333
-----------------------------

我希望每条路线的最终结果都有多少条记录,多少个订单以及所有订单的重量

-----------------------------------------
| RouteID | MODE | SCH DATE |No Of Stop |LastLocatioID|OrderCount|
|   1     | T    | 1/12019  |     3     |      3      |   6      |
|   2     | T    | 2/12019  |     2     |      5      |   4      | 
|   3     | T    | 2/12019  |     1     |      6      |   2      |

如何编写所需的SQL查询?

1 个答案:

答案 0 :(得分:1)

您需要的只是一个简单的分组依据:

SELECT 
    r.ID AS RouteID, 
    r.MODE, 
    r.[SCH DATE],
    COUNT(s.ID) AS [No Of Stop],
    MAX(s.LocationID) AS [LastLocationID],
    COUNT(o.ID) AS OrderCount
FROM 
    @route1 r
INNER JOIN @Stop2 s 
    ON r.ID = s.routeID  
INNER JOIN @StopOrder2 o
    ON s.ID = o.StopID 
GROUP BY 
    r.ID, 
    r.MODE, 
    r.[SCH DATE]

输出:

enter image description here