我有一张包含以下记录的表格:
我需要验证对于Number,Name的每个组合,如果Code为null,则存在具有相同Number,Name的另一个记录,其Code为1.可以有代码1但没有相应代码的记录null
我试过
select t1.name,t1.number,t1.code, t2.code
from
(select distinct name,number,code from dummy
where code is null) t1,
(select distinct name,number,code from dummy
where code is not null) t2
where t1.name=t2.name and t1.number=t2.number
我的想法是检查t1.code中的每个null是否在t2.code中有1。但我在结果中看到了重复。有人可以帮忙吗?
答案 0 :(得分:1)
如果您只是想验证并确保没有(或找不到代码= 1的那些),那么您可以简单地执行此操作:
select number, name from table where code is NULL
minus
select number, name from table where code = 1
答案 1 :(得分:1)
SELECT
T1.number,
T1.name
FROM
My_Table T1
WHERE
T1.code IS NULL AND
NOT EXISTS (
SELECT *
FROM My_Table T2
WHERE
T2.number = T1.number AND
T2.name = T1.name AND
T2.code = 1
)
答案 2 :(得分:0)
尝试使用group-by,switch-case和sum。
以下似乎适用于SQL-Server-Express:
查询:
select num, name, SUM(case code when 1 then 1 else 0 end ) valid_row_count
from SO_37195434 group by num,name;
输出:
num name valid_row_count
1 A 1
2 b 1
2 c 1
更新:
使用sum(isnull(code,0))
也有效!
答案 3 :(得分:0)
select t1.*, t2.code from t t1
left outer join t t2 on t1.number = t2.number and t1.name = t2.name and t2.code = 1
where t1.code is null and t2.number is null;
这将为您提供t1.code
为空的行,但没有对应的t2.code
值为1.