如何在 SQL Server 上的 CASE WHEN 中选择多个列?

How can I SELECT multiple columns within a CASE WHEN on SQL Server?(如何在 SQL Server 上的 CASE WHEN 中选择多个列?)

本文介绍了如何在 SQL Server 上的 CASE WHEN 中选择多个列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经广泛搜索了该网站,但找不到解决方案.

I have searched this site extensively but cannot find a solution.

这是我的查询示例:

SELECT 
   ActivityID,

   Hours = (CASE 
                WHEN ActivityTypeID <> 2 THEN
                     FieldName = (Some Aggregate Sub Query),
                     FieldName2 = (Some other aggregate sub query)
                WHEN ActivityTypeID = 2 THEN
                     FieldName = (Some Aggregate Sub Query with diff result),
                     FieldName2 = (Some Other Aggregate Sub Query with diff result)
           END)

显然我遗漏了很多查询,我只是想看看是否有可能.

obviously I'm leaving out a lot of the query, I just wanted to see if it's possible.

我知道我可能只能做两次CASE",但我想我会问......

I know I probably could just do the "CASE" twice but figured I would ask...

推荐答案

问题在于 CASE 语句无法按照您尝试使用的方式工作.您只能使用它来切换查询中一个字段的值.如果我理解你想要做什么,你可能需要这个:

The problem is that the CASE statement won't work in the way you're trying to use it. You can only use it to switch the value of one field in a query. If I understand what you're trying to do, you might need this:

SELECT 
   ActivityID,
   FieldName = CASE 
                  WHEN ActivityTypeID <> 2 THEN
                      (Some Aggregate Sub Query)
                  ELSE
                     (Some Aggregate Sub Query with diff result)
               END,
   FieldName2 = CASE
                  WHEN ActivityTypeID <> 2 THEN
                      (Some Aggregate Sub Query)
                  ELSE
                     (Some Aggregate Sub Query with diff result)
               END

这篇关于如何在 SQL Server 上的 CASE WHEN 中选择多个列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何在 SQL Server 上的 CASE WHEN 中选择多个列?

基础教程推荐