【问题标题】:SQL Server: Find rows rows in Table1 not in Table2 but need data from tablesSQL Server:在表 1 中查找行,而不是在表 2 中,但需要表中的数据
【发布时间】:2017-04-09 01:20:03
【问题描述】:

我需要查找丢失的行,但是,我需要返回两个表中的数据。我查了谷歌,但没有找到类似的问题。

TableA

thetime  real-time
1        1 pm
2        5 pm
3        7 pm
4        9 pm
5        11 pm

Table2
thedate    transaction_num  thetime
1/1/2000   111                1
1/1/2000   111                4
1/1/2000   111                5
2/1/2000   111                2
2/1/2000   111                4
2/1/2000   222                1
2/1/2000   222                5

我需要从 Table2 中选择在 Table1 中没有时间的日期和 transaction_num,因此 select 语句的结果应该包含不在 table2 中的缺失时间的日期和交易编号:

thedate    transaction_num  thetime
1/1/2000   111                2
1/1/2000   111                3
2/1/2000   111                1
2/1/2000   111                3
2/1/2000   111                5
2/1/2000   222                2
2/1/2000   222                3
2/1/2000   222                4

这是我拥有的代码,但它给了我一个多部分绑定错误:

select t2.thedate, t2.transaction_num, t1.thetime
from table2 t2
where not exists(select t1.thetime
                 from table1 t1
                 where t2.thetime = t1.thetime)

有谁知道如何解决这个问题或可以指出我的答案? 缺少行的堆栈溢出中的大多数问题都涉及从一个表返回数据,但我需要它用于 2 个表。

谢谢

【问题讨论】:

  • 如果您在 t2 中明确检查在 t1 中未找到 thetime 的行,您希望 t1.thetime 出现在您的 select 子句中吗?
  • 我不确定我是否理解。 thetime 2、3 和 1(来自您的预期结果)确实出现在您从 Table A 提供的示例中。你能解释一下吗?
  • 如果您加入t2.thetime = t1.thetime,那么为什么不在您的选择语句中使用t2.thetime
  • 如果我使用 t2.thetime,我将获得我已经拥有的时间。我需要每个交易和日期没有的时间。
  • 我需要交易和日期,但对于没有出现在 table2 中的时间。例如,日期 1/1/2000 的事务 111 的时间 = 2 确实出现在表 2 中,所以我必须让它出现在我的结果中

标签: sql sql-server missing-data


【解决方案1】:

似乎所有日期的所有 transaction_nums 都应该有与之关联的所有时间。否则将被视为丢失。

为此,您最初可以交叉连接 table2 中的不同日期和 transaction_num 以及 table1 中的时间。然后在这个派生表上左连接以获取丢失的行。

select tt.thedate, tt.transaction_num,tt.thetime
    from (
          select * from (
         (select distinct thedate,transaction_num from table2) a cross join
         (select distinct thetime from table1) b
         ) 
        ) tt
         left join table2 t2 on t2.transaction_num=tt.transaction_num and t2.thetime=tt.thetime and tt.thedate=t2.thedate
where t2.transaction_num is null and t2.thedate is null and t2.thetime is null

Sample Demo

【讨论】:

  • 您在示例演示中的代码正是我想要的!太感谢了。我没想到代码会这么复杂。我很惊讶。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-02-10
  • 1970-01-01
  • 1970-01-01
  • 2012-10-20
  • 1970-01-01
  • 2023-03-24
  • 2017-10-09
相关资源
最近更新 更多