【问题标题】:Can't figure out this query无法弄清楚这个查询
【发布时间】:2019-10-16 19:22:54
【问题描述】:

MS-Access 和 SQL 的新手。我有一个包含多个字段的表,我正在尝试创建一个查询,该查询将返回满足特定条件的记录。我正在尝试用 SQL 编写它。

桌子是这样的。 3 列标记为 TxnID、TagNum 和 Plate。 TxnID 字段包含所有唯一编号。 TagNum 和 Plate 字段包含重复的数字和空白记录,我在此处将其列为空白,但它们是空的。实际上有更多的字段和数百万条记录,但这3个字段是查询所需的。仅供参考,我更改了列出的数字,以免暴露任何个人信息。

TxnID           TagNum          Plate
55116236301 403016275   EDT5104
56358456892 403072801   GLY7097
55971408561 403072801   GLY7097
55744617717 403072801   GLY7097
56358641191 BLANKxxxx       GLY7097
56071667010 403072801   GLY7097
56612568234 403072801   GLY7097
56229149821 403072801   GLY7097
56071570614 BLANKxxxx       GLY7097
56229178080 403072801   GLY7097
56612608166 403072801   GLY7097

我希望查询仅返回 TagNum 为空白且 Plate 已填充的记录,如果在其他交易中 TagNum 已填充且 Plate 已填充。本质上,我想找到我们期望特定 TagNum 和特定 Plate 的记录,因为我们在其他交易中看到了这一点,但我们只得到一个 Plate。

我尝试了几种不同的方法,但我有限的经验在这里伤害了我。我在 SELECT 语句中尝试了 COUNT((IIF...AS... ,因为最终我想计算出现次数。我尝试将它放在 WHERE 子句中。没有成功。

任何帮助将不胜感激。

【问题讨论】:

  • 编辑问题并阐明结果集应该是什么。

标签: sql ms-access


【解决方案1】:

考虑:

select *
from mytable t
where 
    (TagNum is null)
    and exists (
        select 1
        from mytable t1
        where t1.Plate = t.Plate and t1.TagNum is not null
    )

这将提取TagNum 为空的记录,以及存在另一条具有相同Plate 和非空TagNum 的记录。

【讨论】:

    【解决方案2】:
    select *
    from table t1
    where tagnum = 'BLANK' and exists(select * from table t2 where t2.Plate = t1.Plate and t2.tagnum <> 'BLANK')
    

    【讨论】:

      【解决方案3】:

      GMB 和 Blindy 的答案都符合您的要求。我正在扩展答案并添加一个返回找到的 TagNum 的列:

      select t1.*, t2.tagnum
      from table t1
      inner join (
         select t.tagnum, t.plate
         from table t
         where t.tagnum is not null
         group by t.tagnum, t.plate
      ) t2 on t2.plate=t1.plate
      where t1.tagnum is null
      

      如果这是您的最终目标,这很容易成为更新声明: 危险且未经测试

      update t1
      set tagnum = t2.tagnum
      from table t1
      inner join (
         select t.tagnum, t.plate
         from table t
         where t.tagnum is not null
         group by t.tagnum, t.plate
      ) t2 on t2.plate=t1.plate
      where t1.tagnum is null
      

      我所写的所有内容都假定并取决于每个盘子只有 1 个 tagnum。如果不存在一对一关系,则应删除此答案。

      【讨论】:

        【解决方案4】:

        此 SQL 将显示空白记录和应该存在的值:

        SELECT Table1.TxnID, Table1.TagNum AS isnull, Table1.Plate, Table1_1.TagNum AS Shouldbe
        FROM Table1 INNER JOIN Table1 AS Table1_1 ON Table1.Plate = Table1_1.Plate
        GROUP BY Table1.TxnID, Table1.TagNum, Table1.Plate, Table1_1.TagNum
        HAVING (((Table1.TagNum) Is Null) AND ((Table1_1.TagNum) Is Not Null));
        

        在 Access 2016 中使用您的数据进行了测试。您应该能够将上面的查询直接剪切并粘贴到 Access 查询中

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-02-11
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多