如何创建视图?

时间:2014-08-28 10:42:14

标签: sql sql-server tsql

我有这些数据。

ID        UserID        Grade
1           1             A
2           1             A
3           1             a
4           1             a
5           1             b
6           1             C
7           1             c
8           1             b
9           2             b
10          2             C
11          1             b
12          2             A

我想为此结果创建视图。

RunningNumber UserID         Result         Count
1                1             a              4
2                1             b              1
3                1             c              2
4                1             b              2
5                2             b              1
6                2             c              1
7                2             a              1

结果将计算列级别(不区分大小写),并且必须按用户ID分组。

我尝试在下面使用。

      SELECT ROW_NUMBER() 
        OVER (ORDER BY Grade) AS RunningNumber , 
       UserID, Grade, COUNT(ID) AS Count 
        FROM Table1
      GROUP BY UserID,Grade;

但这不是我的结果。我想通过选择成绩[按ID排序]来计算。如果下一记录的等级与当前记录相同,则Count将为+1。但如果没有,那将是新纪录。

实施例。从我的数据。

   userID=1 Grade=A ==> record 1 : userID=1 result=a count=1
   userID=1 Grade=A ==> record 1 : userID=1 result=a count=2
   userID=1 Grade=a ==> record 1 : userID=1 result=a count=3
   userID=1 Grade=a ==> record 1 : userID=1 result=a count=4
   userID=1 Grade=b ==> record 2 : userID=1 result=b count=1
   userID=1 Grade=C ==> record 3 : userID=1 result=c count=1
   userID=1 Grade=c ==> record 3 : userID=1 result=c count=2
   userID=1 Grade=b ==> record 4 : userID=1 result=b count=1
   userID=2 Grade=b ==> record 5 : userID=2 result=b count=1
   userID=2 Grade=C ==> record 6 : userID=2 result=c count=1
   userID=1 Grade=b ==> record 4 : userID=1 result=b count=2
   userID=2 Grade=A ==> record 7 : userID=2 result=a count=1

1 个答案:

答案 0 :(得分:0)

据我所知,您只想在userid中添加row_number()以获得所需的输出:

  SELECT ROW_NUMBER() OVER (ORDER BY UserId, Grade) AS RunningNumber, 
         UserID, Grade, COUNT(ID) AS Count 
  FROM Table1
  GROUP BY UserID, Grade
  ORDER BY UserID, Grade;