SQL Server GROUP BY NULL

发布于 2025-01-05 03:19:20 字数 374 浏览 0 评论 0原文

我正在使用 SQL Server,并且必须按几列进行分组,但前提是设置为 true。

DECLARE @setting tinyint
SET @setting = 0

SELECT col1 FROM table1 
GROUP BY col1,
  CASE WHEN @setting = 1 THEN col2 ELSE NULL END

或者我应该默认为 col1,如果设置已设置,我总是使用它进行分组,所以代码将是

CASE WHEN @test = 1 THEN col2 ELSE col1 END

使用 NULL 实际上确实有效,但我无法在互联网上找到示例来证明它是正确的用法。

I am using SQL Server and I have to group by a few columns but only if a setting is true.

DECLARE @setting tinyint
SET @setting = 0

SELECT col1 FROM table1 
GROUP BY col1,
  CASE WHEN @setting = 1 THEN col2 ELSE NULL END

OR should I default to col1 that I always use to group by if the setting is set, so the code would would be

CASE WHEN @test = 1 THEN col2 ELSE col1 END

It does actually work to use the NULL but I can't find an example on the internet to prove that it is correct usage.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

拥抱影子 2025-01-12 03:19:20
SELECT col1 FROM table1 
GROUP BY col1,
  CASE WHEN @setting = 1 THEN col2 ELSE NULL END

您的用法是正确的。你已经知道它有效。
ELSE NULL 隐含在 CASE 中,因此您可以将其写为

GROUP BY col1, CASE WHEN @setting = 1 THEN col2 END

您可以尝试使用诸如

GROUP BY col1, @setting * col2 --数字 col2
GROUP BY col1, COALESCE(NULLIF(@setting,1), col2)

但 CASE 语句实际上展开了一个更好、更简单的计划。

SELECT col1 FROM table1 
GROUP BY col1,
  CASE WHEN @setting = 1 THEN col2 ELSE NULL END

Your usage is correct. You already know it works.
ELSE NULL is implied in CASE, so you could have written it as

GROUP BY col1, CASE WHEN @setting = 1 THEN col2 END

You could try to be coy with variants like

GROUP BY col1, @setting * col2 --for numeric col2
GROUP BY col1, COALESCE(NULLIF(@setting,1), col2)

But the CASE statement actually unrolls to a better, simpler plan.

悍妇囚夫 2025-01-12 03:19:20
DECLARE @setting tinyint
SET @setting = 0

SELECT col1 FROM table1 
GROUP BY col1,
    CASE WHEN @setting = 1 THEN col2 ELSE NULL END

你的第一个例子应该可以工作。
为了进一步说明,当@setting = 1时,您想要group by col1, col2还是group by col1

编辑:你的第一个例子是正确的。

DECLARE @setting tinyint
SET @setting = 0

SELECT col1 FROM table1 
GROUP BY col1,
    CASE WHEN @setting = 1 THEN col2 ELSE NULL END

your first example should work.
For further clarification, do you want to group by col1, col2 or group by col1 when @setting = 1?

edit: Your first example is correct.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文