我需要将所有Start_Stop_ID和End_Stop_ID组合到一个ID列中,但我需要将每个Stop_ID的Start和End数量计算到单独的列中。
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
旅行表
答案 0 :(得分: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,因为我们只计算起始停止ID。创建第二个结果集时,Start将为0,Total(票价)也为0,因为票价仅与开始结果集相关联。
*修正了查询中的拼写错误
答案 1 :(得分:1)
这将计算票价总额并执行计数,但另一列|End|
的逻辑不明确。
select Start_Stop_ID, count(*) num_stops, sum(Current_Fare) AS total
from trip_tableclear
group by Start_Stop_ID
答案 2 :(得分: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;