在三个表上工作,我的分组不起作用

时间:2014-10-11 01:14:03

标签: mysql sql

我必须列出不同的售票数量之间的差异 时间1和时间2之间一行的站点。我有三个表: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.我从我的查询中删除了该组,似乎我有记录而不是两个。

我已经在StackOverflow上尽我所能,但我无法理解我做错的事情?谢谢!

这是我桌子的图像:

image

2 个答案:

答案 0 :(得分:3)

您正在创建两个票价表中具有相同电台的所有行的笛卡尔积,然后将每对中的差异相加。您需要在子查询中分别计算每个表中的总计,然后减去它们。

SELECT s.name, feb1.total - jan18.total AS diff_feb1_jan18
FROM stations AS s
JOIN (SELECT station, SUM(ff) AS total
      FROM fares_feb1
      GROUP BY station) AS feb1
    ON feb1.station = s.station
JOIN (SELECT station, SUM(ff) AS total
      FROM fares_jan18
      GROUP BY station) AS jan18
    ON jan18.station = s.station
WHERE s.line = "Broadway"
ORDER BY s.name

答案 1 :(得分:0)

您需要单独预先聚合每个或者您获得笛卡尔结果...由于查询是针对单个百老汇的,因此在处理来自每个日期数据源的连接时,每个工作站将生成一条记录

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