gpt4 book ai didi

tsql - MAX 和 NULL 的 GROUP BY

转载 作者:行者123 更新时间:2023-12-02 00:52:22 26 4
gpt4 key购买 nike

我想要最大 startdate 但有一个 NULL 数据,它将为 null。

示例数据如下:

DECLARE @Tbl TABLE (Id INT, StartDate DATETIME)

INSERT INTO @Tbl
VALUES (1, NULL),
(1, '2016.07.30'),
(1, '2016.07.05'),
(1, '2016.07.05'),
(2, '2016.07.07'),
(2, '2016.07.05'),
(3, '2016.07.05'),
(3, NULL)

我的查询:

SELECT Id, MAX(StartDate) AS StartDate
FROM @Tbl
GROUP BY Id

输出:

Id          StartDate
----------- ----------
1 2016-07-30
2 2016-07-07
3 2016-07-05

期望的输出:

Id          StartDate
----------- ----------
1 NULL
2 2016-07-07
3 NULL

最佳答案

为了解决这个问题,我们可以使用在两种情况下表现不同的 count 函数:

  1. 当我们使用 count(*) 时,所有行都被计数(也有空值)
  2. 当我们使用 count(someFieldName) 时,只有非空值的行才被计算在内

您可以使用问题中的示例数据在此示例中看到这种不同的行为

select Id, count(*) as count_all, count(StartDate) as count_StartDate
from @Tbl
group by Id;

在输出中我们可以看到这一点

Id  count_all   count_StartDate
1 4 3
2 2 2
3 2 1

我们可以使用这种不同的行为来解决这个查询的问题

select Id, case when count(*) = count(StartDate) 
then max(StartDate)
else null
end as StartDate
from @Tbl
group by Id

在输出上我们可以看到想要的结果

Id  StartDate
1 NULL
2 2016-07-07 00:00:00.000
3 NULL

关于tsql - MAX 和 NULL 的 GROUP BY,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38672110/

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