【问题标题】:Missing data when joining tables连接表时缺少数据
【发布时间】:2019-04-16 21:22:56
【问题描述】:

当我选择一些“季节”变量时,我丢失了数据。我认为,问题在于 where 子句。我用:

"where season = @season Or season IS NULL"

这使我可以从表 a 中获取所有数据,并从表 b 中获取特定季节的数据。这适用于某些季节而不适用于其他季节。对于 2018 赛季,我从表 a 中获取所有行,这就是我想要的。但是如果我使用 2019 赛季,它会忽略任何不包含空值的记录

我正在使用的选择命令是:

SELECT    a.customerid,
          a.lname,
          a.fname,
          b.customerid,
          b.mtg1,
          b.mtg2,
          b.mtg3,
          b.mtg4,
          (COALESCE(Sum(b.mtg1), 0) + COALESCE(Sum(b.mtg2), 0) + COALESCE(Sum(b.mtg3), 0) + COALESCE(Sum(b.mtg4), 0)) AS total
FROM      customer a
LEFT JOIN hours b
ON        a.customerid = b.customerid
WHERE     b.season = @Season
OR        b.season IS NULL
GROUP BY  a.customerid,
          a.lname,
          a.fname,
          b.customerid,
          b.mtg1,
          b.mtg2,
          b.mtg3,
          b.mtg4,
ORDER BY  a.lname 

例如这是我拥有的数据:

这是我获得的 2019 年数据

但这是我想要的 2019 年数据

【问题讨论】:

    标签: sql sql-server tsql sql-server-2012


    【解决方案1】:

    尝试在ON 子句中移动WHERE 子句(您可以省略OR 部分):

    ...
    LEFT JOIN hours b
    ON        a.customerid = b.customerid
    AND       b.season = @Season
    ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-26
      • 2013-10-19
      • 1970-01-01
      • 2015-02-07
      • 2017-05-04
      • 2014-02-20
      • 2016-11-14
      • 2020-10-14
      相关资源
      最近更新 更多