简体   繁体   English

如何在SQL Server 2012中的select查询中将值设置为变量?

[英]How to set value to variable in select query in SQL Server 2012?

I want to generate a sequence for a complex query. 我想为复杂查询生成序列。 For that purpose I have used a variable @rowNo . 为此我使用了变量@rowNo

My logic is :- If a field - isremoved = 0 then increase row number by 1. 我的逻辑是: - 如果一个字段 - 被isremoved = 0则将行数增加1。
If isremoved = 1 then increase row number by 1 only once till you find next 0. 如果isremoved = 1将行数增加1,直到找到下一个0。

This is so far I have done, but it gives me syntax error. 到目前为止,我已经完成了,但它给了我语法错误。

DECLARE @rowNo INT;
SET @rowNo = -1;

SELECT
case when sampleTable.isremoved = 0 then @rowNo + 1
    else @rowNo end
as rowNumber,
X,
Y,
Z
.
.
FROM tbl_sample sampleTable
INNER JOIN tbl_sample_2 sample2 ON sampleTable.id = sample2.id
.
.
.

This is my desire output :- 这是我的愿望输出: -

在此输入图像描述

So what is the right way to achieve this kind of functionality in sql server 2012 ? 那么在sql server 2012实现这种功能的正确方法是什么?

EDIT :- I do have one solution to use sub query to retrieve row number. 编辑: - 我有一个解决方案,使用子查询来检索行号。 But that will hit performance as it is very complex query (more than 20 joins) with huge amount of data. 但这会影响性能,因为它是一个非常复杂的查询(超过20个连接)和大量数据。 So please suggest me an alternative. 所以请建议我一个替代方案。

one way to do this is with subquery: 一种方法是使用子查询:

Select (Select count(*) from tbl_sample
        where id <= a.id 
            and a.isRemoved =1) rowNumber,
   X, Y, Z
From tbl_sample a
     Join tbl_sample_2 b 
         On b.id = a.id

In SQL Server 2012+, you can do what you want with a cumulative sum: 在SQL Server 2012+中,您可以使用累积总和执行所需操作:

SELECT sum(case when sampleTable.isremoved = 0 then 1 else 0 end) over
            (order by . . .)
       . . .

The order by should repeat the order by in the outer query. order by应该在外部查询中重复order by You can also try using order by (select null)) . 您也可以尝试使用order by (select null)) In my experience, this uses the ordering of the data in the outer query, but this is not documented to always work. 根据我的经验,这使用了外部查询中的数据排序,但是没有记录到始终有效。

SQL Server does not allow you to set variables in a SELECT and to return values in a result set. SQL Server不允许您在SELECT设置变量并返回结果集中的值。 One or the other, but not both. 一个或另一个,但不是两个。

I assume your rowNumber logic is equivalent to: if previous isremoved = 0 then increment rowNumber by 1, otherwise keep it as it is. 我假设你的rowNumber逻辑等价于:如果previous isremoved = 0则将rowNumber增加1,否则保持原样。

Using a combination of LAG and SUM ... OVER you can easily implement this logic: 使用LAGSUM ... OVER的组合SUM ... OVER您可以轻松实现此逻辑:

SELECT id, isremoved,
       SUM(IIF(prevFlag = 0, 1, 0)) OVER (ORDER BY id) AS rowNumber
FROM (
SELECT a.id, isremoved,
       COALESCE(LAG(isremoved) OVER (ORDER BY a.id), isremoved) AS prevFlag
FROM tbl_sample AS a
INNER JOIN tbl_sample_2 AS b ON b.id = a.id) AS t

Demo here 在这里演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM