SQL计算每个相同列结果的行号

时间:2014-12-02 08:10:01

标签: sql-server rowcount

首先,抱歉我的英语不好。我在创建SQL语句时遇到问题。

我创建了一个行计数列:

SELECT 
    ROW_NUMBER() OVER(ORDER BY KNR DESC) AS Row, 
    KNR, text, DATUM 
FROM 
    KURSTAGE 
WHERE 
    (KNR like '%E3%') AND (TEXT = 'TEXT') AND ( datum >= '02.12.2014') AND (KNR like 'O%') 

结果如下:

Row Result1 Result2 etc.
------------------------------------------------
1   OE3WU9B TestTest    2015-06-28 00:00:00.000
2   OE3WU9B TestTest    2015-06-28 00:00:00.000
3   OE3WU9B TestTest    2015-06-07 00:00:00.000
4   OE3WU9B TestTest    2015-05-30 00:00:00.000
5   OE3WU9B TestTest    2015-05-10 00:00:00.000
6   OE3ST9B TestTest    2015-05-31 00:00:00.000
7   OE3ST9B TestTest    2015-05-17 00:00:00.000
8   OE3ST9B TestTest    2015-05-10 00:00:00.000
9   OE3ST9B TestTest    2015-04-26 00:00:00.000
10  OE3ST9B TestTest    2015-04-19 00:00:00.000

是否可以创建一个ROW计数,该计数从Result1的相同结果开始时从1开始计数?

例如:

Row Result1 Result2 etc.
1   OE3WU9B TestTest    2015-06-28 00:00:00.000
2   OE3WU9B TestTest    2015-06-28 00:00:00.000
3   OE3WU9B TestTest    2015-06-07 00:00:00.000
4   OE3WU9B TestTest    2015-05-30 00:00:00.000
5   OE3WU9B TestTest    2015-05-10 00:00:00.000
**1**   OE3ST9B TestTest    2015-05-31 00:00:00.000
2   OE3ST9B TestTest    2015-05-17 00:00:00.000
3   OE3ST9B TestTest    2015-05-10 00:00:00.000
4   OE3ST9B TestTest    2015-04-26 00:00:00.000
5   OE3ST9B TestTest    2015-04-19 00:00:00.000

1 个答案:

答案 0 :(得分:0)

SELECT ROW_NUMBER() OVER
(PARTITION BY KNR ORDER BY KNR,DATUM DESC) AS Row, 
KNR, 
text, 
DATUM FROM KURSTAGE 
WHERE (KNR like '%E3%') 
AND (TEXT = 'TEXT') 
AND ( datum >= '02.12.2014') 
AND (KNR like 'O%')