2017-12-02 166 views
0

我需要將所有Start_Stop_ID和End_Stop_ID組合到一個ID列中,但我需要將每個Stop_ID的開始和結束數計入單獨的列中。MySQL選擇查詢:計算計數並獲得總計

Start_Stop_ID的每一行都有Current_Fare。我需要計算與Start_Stop_ID關聯的Current_Fare的總數,而不是End_Stop_ID。

 
The columns would be: 
ID | Start | END | TOTAL 

Example: 
There would be rows such as 
E1  | 1 | 0 | 3.50 
BUSDOME | 3 | 0 | 18.50 (BUSDOME has 3 Start_Stop_ID, 10.50, 4.00 and 4.00) 
N4  | 1 | 3 | 1.50 
E5  | 2 | 0 | 6.00 (E5 has 2 Start_Stop_ID, 3.00 and 3.00) 
E7  | 0 | 1 | 0.00 

旅行表

Trip Table

回答

2

這是我的解決方案:

SELECT i.ID, SUM(i.Start) Start, SUM(i.End) End, SUM(i.Total) Total FROM (
    SELECT Start_Stop_ID ID, COUNT(Start_Stop_ID) AS Start, 0 AS End, SUM(Current_Fare) AS Total 
    FROM trip_table GROUP BY ID 
    UNION ALL 
    SELECT End_Stop_ID ID, 0 AS Start, COUNT(End_Stop_ID) AS End, 0 AS Total 
    FROM trip_table WHERE End_Stop_ID IS NOT NULL GROUP BY ID 
    ORDER BY ID ASC) i 
GROUP BY i.ID 

什麼這個查詢所做的就是創建一個基於Start_Stop_ID結果,並根據End_Stop_ID另一個結果集,然後使用UNION ALL之前,將它們組合總計總和。

創建第一個結果集時,End將爲0,因爲我們只計算起始停止標識。創建第二個結果集時,Start將爲0,Total(票價)也爲0,因爲票價僅與起始結果集相關聯。

*修正筆誤查詢

1

這將計算出車費總和執行計數,但其他列|End|的邏輯是不明確的。

select Start_Stop_ID, count(*) num_stops, sum(Current_Fare) AS total 
from trip_tableclear 
group by Start_Stop_ID 
+0

我想的第一列是在Start_Stop_ID每個ID和在End_Stop_ID每個ID的第二計數的計數。因此,N4在Start_Stop_ID中出現一次,在End_Stop_ID中出現3次。然後,:N4 | 1 | 3 | 1.50 看起來總數僅僅基於Current_Fare中的ID列出現在第一列中。 – Arcesilas

+0

我想計算End_Stop_ID的總數並將其放入列中,但它與Start_Stop_ID的計數位於同一行。 –

+0

正如@Arcesilas所說,Current_Fare的總和只是基於Start_Stop_ID –

0

解查詢:

SELECT Start_Stop_ID as 'ID', count(num_stops) as 'Count', SUM(Current_Fare) as 'Total Fare' FROM trip_tableclear GROUP BY Start_Stop_ID;