我正在加入三张桌子并计算MY SQL FIDDLE。在这个查询中,我想再多计算total_trip
,这意味着我已经加入了trip_details
表,在这个表中取所有计数即总行程计数,我无法编写子查询。
SELECT COUNT(T.tripId) as Escort_Count,
(
SELECT COUNT(*) FROM
(
SELECT a.allocationId
FROM escort_allocation a
INNER JOIN cab_allocation c ON a.allocationId = c.allocationId
WHERE c.allocationType = 'Adhoc Trip'
GROUP BY a.allocationId
) AS Ad
) AS Adhoc_Trip_Count
FROM
(
SELECT a.tripId FROM
trip_details a
INNER JOIN
escort_allocation b
ON a.allocationId = b.allocationId
GROUP BY a.allocationId
) AS T
答案 0 :(得分:0)
使用以下子查询:
<强>查询:强>
SELECT COUNT(T.tripId) as Escort_Count,
(
SELECT COUNT(*) FROM
(
SELECT a.allocationId
FROM escort_allocation a
INNER JOIN cab_allocation c ON a.allocationId = c.allocationId
WHERE c.allocationType = 'Adhoc Trip'
GROUP BY a.allocationId
) AS Ad
) AS Adhoc_Trip_Count,
(SELECT COUNT(id) FROM trip_details) as Total_Count
FROM
(
SELECT a.tripId FROM
trip_details a
INNER JOIN
escort_allocation b
ON a.allocationId = b.allocationId
GROUP BY a.allocationId
) AS T
结果:
Escort_Count Adhoc_Trip_Count Total_Trip
5 2 7
查看:
答案 1 :(得分:0)
SELECT COUNT(DISTINCT Z.allocationId) Escort_Count,SUM(CASE WHEN allocationType='Adhoc Trip' THEN 1 END) Adhoc_Trip_Count FROM (
SELECT DISTINCT a.allocationId, allocationType FROM escort_allocation a
INNER JOIN cab_allocation c ON a.allocationId = c.allocationId
INNER JOIN trip_details TD ON a.allocationId = TD.allocationId
GROUP BY a.allocationId
)Z;
<强> OR
强>
SELECT Escort_Count,Adhoc_Trip_Count,Adhoc_Trip_Count+Escort_Count TOTAL FROM(
SELECT COUNT(DISTINCT Z.allocationId) Escort_Count,SUM(CASE WHEN allocationType='Adhoc Trip' THEN 1 END) Adhoc_Trip_Count,COUNT(D) FROM (
SELECT DISTINCT a.allocationId, allocationType,SUM(1) D FROM escort_allocation a
INNER JOIN cab_allocation c ON a.allocationId = c.allocationId
INNER JOIN trip_details TD ON a.allocationId = TD.allocationId
GROUP BY a.allocationId
)Z
)ZZ;
您可以尝试以上查询。
绝对会帮助你。
答案 2 :(得分:-1)
这是你想要的吗?
SELECT td.tripId, COUNT(*) as total, SUM(ea.allocationType = 'Adhoc Trip') as adhocs
FROM trip_details td JOIN
escort_allocation ea
ON td.allocationId = ea.allocationId
GROUP BY td.tripId;