簡體   English   中英

SQL Server從colvalue = 0的排序表開始計數行數

[英]SQL Server counting number of rows from beginning of sorted table where colvalue = 0

我們有SQL Server 2008 R2。 我有桌子MyTable

我需要:

  1. Nr (ORDER BY MyTable.NR)列排序Nr (ORDER BY MyTable.NR)

  2. 從此排序表的開始算起有多少個值等於0(請注意,它已經被NR排序)( MyTable.Value = 0 )。

例如,如果MyTable具有以下值:

NR Value
2  0
1  0
3  5
4  0

那么我必須得到count = 2,因為如果按Nr排序此表,我們將有兩行,其中從表的開頭開始Value = 0。

您可以使用NOT EXISTS來排除具有NRValue <> 0的行的所有行。

DECLARE @T TABLE (NR INT, Value INT);
INSERT @T VALUES (2, 0), (1, 0), (3, 5), (4, 0);

SELECT  COUNT(*)
FROM    @T AS t1
WHERE   t1.Value = 0
AND     NOT EXISTS
        (   SELECT  1
            FROM    @T AS t2
            WHERE   t2.Value <> 0
            AND     t2.NR < t1.NR
        );

您可以使用謂詞Value = 0來過濾數據,然后使用row_number過濾的數據進行編號,然后對分配的編號等於原始編號的行進行計數:

declare @data table (NR int, Value int);
insert into @data values
    (2, 0), (1, 0), (3, 5), (4, 0);

;with
step1 as (select NR from @data where Value = 0),
step2 as (select NR, rn = row_number() over (order by NR) from step1)
select count(1)
from step2
where NR = rn;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM