且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在sql server中将case值设置为变量?

更新时间:2023-01-31 15:39:17

你真的不能这样做 - 因为SELECT没有直接替换将返回多个价值,因此值得表 - 这使得过滤有趣!



你可以选择进入一个临时表,如果这是你想要做的?


 声明  @ temptable   table  

var1 int




插入 进入 @temptable 选择 CASE WHEN n_cong> = n_bjp AND n_cong> = n_aap 那么 n_cong
WHEN n_bjp> = n_aap 那么 n_bjp
ELSE n_aap
END ) - n_winby AS againstpartyvote

FROM m_assembly_election1993 order by n_winby desc

选择 var1 来自 @不是Temptable 跨度>


Code is :


SELECT CASE WHEN Cong >= BJP AND Cong >= AAP THEN Cong
                   WHEN BJP >= AAP THEN BJP
                   ELSE AAP
           END AS maxvote, Winner AS [Party Name] FROM TableName




I wanna use a variable in place of maxvote alias, Because I want to filter another data based on this variable.

You can't really do that - there is no direct replacement because the SELECT will return multiple values and thus a table worth - which makes it "interesting" to filter on!

You can SELECT into a temporary table, if that's what you are trying to do?


declare @temptable table
(
var1 int

)


insert into @temptable select (CASE WHEN n_cong >= n_bjp AND n_cong >= n_aap THEN n_cong
                   WHEN n_bjp >= n_aap THEN n_bjp
                   ELSE n_aap
           END)-n_winby AS againstpartyvote

            FROM m_assembly_election1993 order by n_winby desc

            select var1 from @temptable