如何在SQL Server上的CASE中选择多个列? [英] How can I SELECT multiple columns within a CASE WHEN on SQL Server?
本文介绍了如何在SQL Server上的CASE中选择多个列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经对该网站进行了广泛搜索,但是找不到解决方法.
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中选择多个列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文