我使用 Access 2010。
我得到了一个没有主键的表,别问我为什么。 看起来像这样。
Code | Dept | Name | Status |
================================
AA | 01 | John | A |
AB | 00 | Bert | A |
AB | 01 | Yoan | A |
BB | 00 | Luke | A |
我想一次选择每个代码。如果代码在两个部门下,我只想选择 dept01 中的信息。
所以,我想要这个结果:
Code | Dept | Name | Status |
================================
AA | 01 | John | A |
AB | 01 | Yoan | A |
BB | 00 | Luke | A |
我知道我可以在 SQL Server 中使用 Case,但在 Access 中,它不想协作。
感谢您的帮助!
菲尔
最佳答案
嗯。这可能有点棘手。如果一个代码最多只出现两次(如在您的示例数据中),那么您可以:
select t.*
from t
where dept = '01'
union all
select t.*
from t
where dept <> '01' and
not exists (select 1 from t as t2 where t2.code = t.code);
这将返回“01”中的所有内容以及代码不在“01”中的另一个部门的所有行。
编辑:
如果每个代码有多行(每个部门只有一行),那么这也有效:
select t.*
from t inner join
(select code, max(iif(dept = '01', 1 0)) as has01, min(dept) as mindept
from t
group by code
) as tt
on t.code = tt.code
where t.dept = '01' or (t2.has01 = 0 and t.dept = t2.mindept);
关于sql - 如果一列满足条件,如何选择一行,如果不满足,则选择另一列? [ Access 2010],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34005980/