gpt4 book ai didi

sql - 将空值视为唯一值

转载 作者:行者123 更新时间:2023-12-03 14:30:21 26 4
gpt4 key购买 nike

我需要在列上计算不同的值,例如:

Hours
1
1
2
null
null
null

结果必须是: 3 。我的查询是:
select count(distinct hour) from hours;

但它返回:2.我还测试了:
select count(*) from hours group by hour

但它返回三行:
(1) 3
(2) 2
(3) 1

我如何将空值算作1值,并使用distinct避免计算重复值?

我正在学习高级SQL,他们希望我对所有解决方案有以下要求:

Try to minimize the number of subqueries you need to solve the query. Furthermore, you are not allowed to use the following constructions:

  • SELECT in the FROM or SELECT. You are allowed to have subqueries (SELECT in the WHERE or HAVING)
  • Combinations of aggregation functions such as COUNT (COUNT. ..)), SUM (COUNT. ..)) and the like.
  • UNION if you can avoid it.
  • Non-standard functions (such as NVL)
  • CASE

最佳答案

select  count(distinct col1) + count(distinct case when col1 is null then 1 end)
from YourTable

关于sql - 将空值视为唯一值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15040602/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com