如何在 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
相关文章