无法找出此查询

时间:2019-10-16 19:22:54

标签: sql ms-access

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

表是这样的。 3列标签为TxnID,TagNum和Plate的列。 TxnID字段包含所有唯一编号。 TagNum和Plate字段包含重复的数字和空白记录,我在此处将其列为BLANK,但irl它们为Null。实际上有更多的字段和数百万条记录,但是这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子句中。没有成功。

任何帮助将不胜感激。

4 个答案:

答案 0 :(得分:0)

select *
from table t1
where tagnum = 'BLANK' and exists(select * from table t2 where t2.Plate = t1.Plate and t2.tagnum <> 'BLANK')

答案 1 :(得分:0)

考虑:

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 :(得分:0)

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的盘子。如果没有一对一的关系,则应删除此答案。

答案 3 :(得分:0)

此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));

enter image description here

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