2013-08-23 43 views
0

我需要幫助根據特定值的出現編號數據。根據事件編號數據

讓我們考慮輸入

Col1 Col2 
1 a 
2 1 
3 2 
4 3 
5 a 
6 1 
7 4 
8 a 
9 2 
10 3 

我想根據 'A' 在COL2的occurence給它們編號。輸出應該看起來像

Col1 Col2 Result 
1 a 1 
2 1 1 
3 2 1 
4 3 1 
5 a 2 
6 1 2 
7 4 2 
8 a 3 
9 2 3 
10 3 3 
+0

數據沒有訂單,除了在查詢中明確指定的訂單。 – podiluska

+0

因此1-4和5-7和8-10是邏輯組,您想按這些組排序? –

+0

是的,首次出現的「a」結果中應該有值「1」,它應該保持相同,直到第二次出現「a」。根據col2中出現'a'增加結果值 –

回答

1

您可以使用遊標。

1) Create a temp table 
2) Output the result to a cursor 
3) Loop throught the cursor and update the temp table 
4) Select from the temp table. 

編輯:

我不知道這是多麼有用將但這句話會得到U U想要的東西,而無需使用鼠標。

SELECT [Col1] 
     ,[Col2] 
     , (select count(*) from Table_1 where Col2 = 'a' and Col1 <= t1.Col1) 
    FROM [Table_1] t1 
+0

謝謝,但我想在查詢中完成此操作,而不是使用PL/SQL塊 –

+0

如果這有幫助,我已修改了我的答案。 –

+0

謝謝,只需稍作更改,我就可以將其用於我的要求。 –

1
Declare @a table (Col1 int,Col2 Char(1)) 
Insert into @a Values (1,'a'),(2,'1'),(3,'2'),(4,'3'),(5,'a'),(6,'1'),(7,'4'),(8,'a'),(9,'2'),(10,'3'); 

;With CTE as 
(
Select *,Row_Number() OVER (Order by Col1) as rn from @a 
) 


Select a.Col1,a.Col2, 
(Select COUNT(Col2) from CTE a2 where a2.Col2=a.Col2 and a2.rn <= a.rn) 
from CTE a 
+0

謝謝。它幫助了我。 –

1

作爲一個說明,在SQL Server 2012中,您可以用累積和做到這一點:

select col1, col2, 
     sum(case when col2 = 'a' then 1 else 0 end) over (order by col1) as result 
from t; 

中累積在支持窗口/解析函數其他數據庫的支持好。

+0

其分析功能更簡單。謝謝。 –