我必须列出在不同地方售出的门票数量之间的差异
在time1和time2之间的一条线的站点。我有三个表:time1,time 2和place。
create table fares_jan18 (
station varchar(100),
ff int
);
create table fares_feb1 (
station varchar(100),
ff int
);
create table stations (
name varchar(100),
line varchar(50)
);
我正在使用此查询:
SELECT
fares_jan18.station AS name,
SUM(fares_feb1.ff - fares_jan18.ff) AS diff_feb1_jan18
FROM
fares_jan18
JOIN fares_feb1 ON fares_jan18.station = fares_feb1.station
JOIN stations ON fares_jan18.station = stations.name
WHERE
stations.line ="Broadway"
GROUP BY
name
ORDER BY
name;
它的确为我提供了正确的表,但是只要有一条以上的记录,我就会得到重复的总和。例如,具有两个值的桩号的结果应为33254,这给了我66508。我从查询中删除了“ group by”,看来我有记录而不是两个。
我已经阅读了StackOverflow上的所有文章,但无法理解我做错了什么吗?谢谢!!
这是我桌子的图片:
最佳答案
您需要分别对每个站点进行预聚合,否则将获得笛卡尔结果...由于查询是针对单个百老汇的,因此从每个日期数据源进行联接时,每个工作站将产生一条记录
SELECT
justF18.name,
justFeb1.SumFF - justF18.SumFF as FF_Diff
from
( SELECT f18.station AS name,
SUM(f18.ff) AS Sumff
FROM
fares_jan18 f18
JOIN stations s ON f18.station = s.name
AND s.line = "Broadway"
group by
f18.station ) justF18
JOIN
( SELECT feb1.station AS name,
SUM(feb1.ff) AS Sumff
FROM
fares_feb1 feb1
JOIN stations s ON feb1.station = s.name
AND s.line = "Broadway"
group by
feb1.station ) justFeb1
ON justF18.name = justFeb1.name
order by
JustFeb18.name
关于mysql - 在三个表上工作,按我的分组不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26310059/