How can I SELECT multiple columns within a CASE WHEN on SQL Server?(如何在 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 中选择多个列?
基础教程推荐
- 将数据从 MS SQL 迁移到 PostgreSQL? 2022-01-01
- 无法在 ubuntu 中启动 mysql 服务器 2021-01-01
- 如何在 SQL Server 的嵌套过程中处理事务? 2021-01-01
- ERROR 2006 (HY000): MySQL 服务器已经消失 2021-01-01
- 在 VB.NET 中更新 SQL Server DateTime 列 2021-01-01
- SQL Server:只有 GROUP BY 中的最后一个条目 2021-01-01
- SQL Server 2016更改对象所有者 2022-01-01
- Sql Server 字符串到日期的转换 2021-01-01
- 使用pyodbc“不安全"的Python多处理和数据库访问? 2022-01-01
- SQL Server 中单行 MERGE/upsert 的语法 2021-01-01