【问题标题】:How to omit aggregated row when columns are null当列为空时如何省略聚合行
【发布时间】:2021-05-07 02:44:44
【问题描述】:

我有一个 EAV 表,我将其转为几列。

如果[h1][h2][h3] 都是null,我不想返回一行。

declare 
@h1 nvarchar(10) = 'A',
@h2 nvarchar(10) = 'B',
@h3 nvarchar(10) = 'C'

select 
[id],
[h1]  = isNull(max( case when [key] = @h1 then [value] end ), ''),
[h2]  = isNull(max( case when [key] = @h2 then [value] end ), ''),
[h3]  = isNull(max( case when [key] = @h3 then [value] end ), ''),
from some..db
group by [id]
having (
  and max( case when [key] = @h1 then [value] end) is not null
  and max( case when [key] = @h2 then [value] end) is not null
  and max( case when [key] = @h3 then [value] end) is not null
)

如何旋转此表并删除 [h] 列中具有 null 值的行?

【问题讨论】:

  • 我有点迷路了。您使用的是isnull(),所以返回的值都不是NULL
  • 我认为,因为我在 having 子句中重新评估 isnull() 将被忽略。 having 子句中的 <> '' 会解决这个问题吗?
  • No <> '' 不行,也不要在HAVING 中使用ISNULL,只需将OR 改为AND
  • 如果 全部为空,我不想返回一行 - 所以直接将其转换为过滤器:not(col1 is null and col2 is null and col3 is null)

标签: sql sql-server null pivot


【解决方案1】:

基于来自@Charlieface 的反馈。

declare 
@h1 nvarchar(10) = 'A',
@h2 nvarchar(10) = 'B',
@h3 nvarchar(10) = 'C'

select 
[id],
[h1]  = isNull(max( case when [key] = @h1 then [value] end ), ''), 
[h2]  = isNull(max( case when [key] = @h2 then [value] end ), ''),
[h3]  = isNull(max( case when [key] = @h3 then [value] end ), ''),
from some..db
group by [id]
having (
  max( case when [key] = @h1 then [value] end) is not null
  or max( case when [key] = @h2 then [value] end) is not null
  or max( case when [key] = @h3 then [value] end) is not null
)

或者通过@astentx替代having子句

having max(case when [key] in (@h1, @h2, @h3) then 1 end) is not null

【讨论】:

  • 由于您需要找到 any 不为 null,因此可以将其简化为 having max(case when [key] in (@h1, @h2, @h3) then 1 end) is not null,因为此 case 表达式将检查是否存在任何感兴趣的值。只是不要复制粘贴。或者使用pivot直接过滤coalesce([h1], [h2], [h3]) is not null
猜你喜欢
  • 1970-01-01
  • 2014-08-10
  • 1970-01-01
  • 2015-05-02
  • 2013-08-31
  • 2021-11-20
  • 2023-04-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多