【问题标题】:How to select the max value by condition?如何按条件选择最大值?
【发布时间】:2021-03-26 01:37:37
【问题描述】:

如果满足条件我想取最大值,否则取所有值

select debtresidentid, [priority], IIF([priority] = 1, max(phonenum), phonenum) as phonenum
from debtphone
group by debtresidentid, [priority]

我得到一个错误:

PHONENUM' 在选择列表中无效,因为它既不包含在聚合函数中,也不包含在 GROUP BY 子句中。

如果我尝试按 [phonenum] 分组,我将获得所有价值。

【问题讨论】:

  • 请提供样本数据和期望的结果。

标签: sql sql-server sql-server-2008 iif


【解决方案1】:

你可以这样表述:

select debtresidentid,
       max(case when [priority] = 1 then phonenum end) as phonenum
from debtphone
group by debtresidentid;

请注意,条件逻辑的 SQL 标准是 CASE,而不是 IIF()。我强烈建议您使用标准 SQL 语法,除非您有充分的理由使用定制语法。

编辑:

哦,我想我明白了。您想返回所有priority = 1。否则所有数字。为此,请使用窗口函数:

select debtresidentid, phonenum
from (select p.*, 
             sum(case when priority = 1 then 1 else 0 end) over (partition by debtresidentid) as num_priority_1
      from debtphone p
     ) p
where num_priority_1 > 0 and priority = 1 or
      num_priority_1 = 0
order by debtresidentid;

【讨论】:

  • 如果 '[priority] = 1' 我想返回所有值
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-11-04
  • 2022-01-03
  • 1970-01-01
  • 1970-01-01
  • 2022-06-23
  • 1970-01-01
  • 2015-09-24
相关资源
最近更新 更多