SELECT
Ticket_No,
_id,
Date_Add,
trip_no,
f.Location_Name AS FromName,
From_LocationID,
To_LocationID,
t.Location_Name AS ToName
FROM Tbl_InOut
LEFT JOIN Tbl_Ticket
ON Tbl_InOut._id = Tbl_Ticket.Trip_ID
LEFT JOIN Tbl_Location AS f
ON f.Location_ID = Tbl_Ticket.From_LocationID
LEFT JOIN Tbl_Location AS t
ON t.Location_ID = Tbl_Ticket.To_LocationID
UNION ALL
SELECT Ticket_No,
_id,
Date_Add,
trip_no,
f.Location_Name AS FromName,
From_LocationID,
To_LocationID,
t.Location_Name AS ToName
FROM Tbl_Ticket
LEFT JOIN Tbl_InOut
ON Tbl_InOut._id = Tbl_Ticket.Trip_ID
LEFT JOIN Tbl_Location AS f
ON f.Location_ID = Tbl_Ticket.From_LocationID
LEFT JOIN Tbl_Location AS t
ON t.Location_ID = Tbl_Ticket.To_LocationID
首先是Tbl_InOut左加入Tbl_Ticket和 Tbl_Location LEFT JOIN与Tbl_Ticket这是结果,现在我想计算从From_LocationID到To_Location的数据量
示例Ticket_No 1,2,3,4,5是from_LocationID 1 to To_LocationID 3 total是5所以在To_Name列旁边将添加一个列名TotalCount,而TotalCount列值下的这5行是5,少了我不解释请看上面的图片我添加了totalCount列与我想要的值
1计数器工作正常但是,2计数数据将变为双倍,如何解决,这是我的SQL
SELECT
Ticket_No,_id,Date_Add, trip_no,f.Location_Name as FromName,From_LocationID,To_LocationID,t.Location_Name as ToName,PriceType_ID,Amount,
(SELECT COUNT(*) FROM Tbl_Ticket WHERE Trip_ID = Tbl_InOut._id AND Tbl_Ticket.From_LocationID = f.Location_ID AND t.Location_ID = Tbl_Ticket.To_LocationID AND Tbl_Ticket.PriceType_ID = 0) AS NormalCount,
(SELECT COUNT(*) FROM Tbl_Ticket WHERE Trip_ID = Tbl_InOut._id AND Tbl_Ticket.From_LocationID = f.Location_ID AND t.Location_ID = Tbl_Ticket.To_LocationID AND Tbl_Ticket.PriceType_ID > 0) AS DiscountCount
FROM Tbl_InOut
LEFT JOIN Tbl_Ticket ON Tbl_InOut._id = Tbl_Ticket.Trip_ID
LEFT JOIN Tbl_Location as f On f.Location_ID = Tbl_Ticket.From_LocationID
LEFT JOIN Tbl_Location as t On t.Location_ID = Tbl_Ticket.To_LocationID
UNION ALL
SELECT
Ticket_No,_id,Date_Add, trip_no,f.Location_Name as FromName,From_LocationID,To_LocationID,t.Location_Name as ToName ,PriceType_ID,Amount,
(SELECT COUNT(*) FROM Tbl_Ticket WHERE Trip_ID = Tbl_InOut._id AND Tbl_Ticket.From_LocationID = f.Location_ID AND t.Location_ID = Tbl_Ticket.To_LocationID AND Tbl_Ticket.PriceType_ID = 0) AS NormalCount,
(SELECT COUNT(*) FROM Tbl_Ticket WHERE Trip_ID = Tbl_InOut._id AND Tbl_Ticket.From_LocationID = f.Location_ID AND t.Location_ID = Tbl_Ticket.To_LocationID AND Tbl_Ticket.PriceType_ID > 0) AS DiscountCount
FROM Tbl_Ticket
LEFT JOIN Tbl_InOut ON Tbl_InOut._id = Tbl_Ticket.Trip_ID
LEFT JOIN Tbl_Location as f On f.Location_ID = Tbl_Ticket.From_LocationID
LEFT JOIN Tbl_Location as t On t.Location_ID = Tbl_Ticket.To_LocationID
答案 0 :(得分:1)
您可以使用相关子查询来计算匹配的记录数:
SELECT
...,
(SELECT COUNT(*)
FROM Tbl_Ticket
WHERE Trip_ID = Tbl_InOut._id
) AS TotalCount
FROM ...