where 中 使用 case when语句的问题

秋天之落叶 2019-12-25 12:42:46
select ... from 表1 a,表2 b
where a.中心=b.中心 and a.分组=b.分组 and a.类别=b.细项
and (case when b.分组 ='' or b.分组 is null then b.分组 else a.分组 end)= b.分组
and (case when b.姓名 ='' or b.姓名 is null then b.姓名 else a.姓名 end) =b.姓名
group by ...

请教一下, b.姓名 字段有 '' 有 NULL,单独在b表中使用 where 姓名 ='' or 姓名 is null条件有效,结果正确;单独case when b.姓名 =''或单独case when b.姓名 is null也成立,结果正确;就是 (case when b.姓名 ='' or b.姓名 is null then b.姓名 else a.姓名 end) =b.姓名使用时,总是漏掉NULL的值,这是什么原因?
如果是因为 NULL=b.姓名 造成的,因该怎么修改一下?
...全文
188 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
秋天之落叶 2019-12-28
  • 打赏
  • 举报
回复
感谢两位的帮助,花了几天时间,终于找到了问题所在,主要还是group by的问题,在select中加上 (case when b.分组<>'' or b.分组 is not bull then b.分组 when b.姓名<>'' or b.姓名 is not bull then b.姓名 end) as 分组姓名,from中加上 and (a.评价人职务=b.评价人职务 or a.评价人姓名=b.评价人姓名),结果正确。
因为两个条件互斥,所以一直没有解决,一直使用 union,这回没问题了。
RINK_1 2019-12-27
  • 打赏
  • 举报
回复
select * from 表 where (a.中心=b.中心) and ((isnull(a.分组,'')<>'' and isnull(b.分组,'')<>'' and a.分组=b.分组) or (isnull(a.姓名,'')<>'' and isnull(b.姓名,'')<>'' and a.姓名=b.姓名))
秋天之落叶 2019-12-27
  • 打赏
  • 举报
回复
where a.中心=b.中心 and b.分组=(case when b.分组 ='' or b.分组 =isnull(b.分组,'') then '' else a.分组 end) and b.姓名=(case when b.姓名='' or b.姓名=isnull(b.姓名,'') then '' else a.姓名 end)
这样吗?
秋天之落叶 2019-12-27
  • 打赏
  • 举报
回复
引用 2 楼 吉普赛的歌 的回复:
a.姓名=b.姓名 or isnull(b.姓名, '')=''


针对这句:
where a.中心=b.中心
and (case when b.分组 ='' or b.分组 is null then b.分组 else a.分组 end)= b.分组
and (case when b.姓名 ='' or b.姓名 is null then b.姓名 else a.姓名 end) =b.姓名
假如:有分组的没有姓名,有姓名的没有分组
我如何写才能使的这两种条件并存:
select * from 表 where a.中心=b.中心 and(IF b.分组<>'' or b.分组 is not NULL then a.分组=b.分组) and (IF b.姓名<>'' or b.姓名is not NULL then a.姓名=b.姓名)
最后的结果应该是
select * from 表 where a.中心=b.中心 and a.分组=b.分组
union
select * from 表 where a.中心=b.中心 and a.姓名=b.姓名
吉普赛的歌 版主 2019-12-25
  • 打赏
  • 举报
回复
a.姓名=b.姓名 or isnull(b.姓名, '')=''
秋天之落叶 2019-12-25
  • 打赏
  • 举报
回复
OK,解决了
(a.姓名=b.姓名 or b.姓名='' or b.姓名 is null)
是我想的太复杂了,哈哈

34,591

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧