MySQL选择查询:计算计数并获得总计
我需要将所有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
旅行表
回答:
这是我的解决方案:
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,因为票价仅与起始结果集相关联。
*修正笔误查询
回答:
这将计算出车费总和执行计数,但其他列|End|
的逻辑是不明确的。
select Start_Stop_ID, count(*) num_stops, sum(Current_Fare) AS total from trip_tableclear
group by Start_Stop_ID
回答:
解查询:
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;
以上是 MySQL选择查询:计算计数并获得总计 的全部内容, 来源链接: utcz.com/qa/258838.html