1 CREATE TABLE [ Test ]
2 (
3 [ StudentID ] [ bigint ] NOT NULL ,
4 [ ClassID ] [ bigint ] NOT NULL ,
5 [ TestScore ] [ decimal ] ( 4 , 1 ) NOT NULL
6 ) ON [ PRIMARY ]
7 GO
8
9 INSERT INTO [ Test ]
10 VALUES ( 100001 , 100 , 90 ),
11 ( 100002 , 100 , 85.5 ),
12 ( 100003 , 100 , 80 ),
13 ( 100004 , 100 , 80 ),
14 ( 100005 , 100 , 74 ),
15 ( 101001 , 101 , 94 ),
16 ( 101002 , 101 , 85.5 ),
17 ( 101003 , 101 , 85.5 )
18 GO
19
1 SELECT * ,
2 ROW_NUMBER() OVER ( ORDER BY TestScore DESC ) as RN,
3 RANK() OVER ( ORDER BY TestScore DESC ) as R,
4 DENSE_RANK() OVER ( ORDER BY TestScore DESC ) as DR,
5 NTILE( 3 ) OVER ( ORDER BY TestScore DESC ) as N3
6 FROM [ TEST ]
7 GO
8
1 SELECT * , ROW_NUMBER() OVER ( ORDER BY TestScore DESC ) as RN
2 FROM [ TEST ]
3 WHERE RN BETWEEN 6 AND 10
4
1 SELECT * , RANK() OVER (PARTITION BY ClassID ORDER BY TestScore DESC ) as R
2 FROM [ Test ]
3
1 ; WITH Test_RN
2 AS
3 (
4 SELECT StudentID, ClassID, TestScore,RANK() OVER (PARTITION BY ClassID ORDER BY TestScore DESC ) as RN
5 From Test
6 )
7 Select * FROM Test_RN WHERE RN = 1
1 CREATE TABLE [ Dept ]
2 (
3 [ DeptID ] [ bigint ] NOT NULL ,
4 [ DeptName ] [ nvarchar ] ( 50 ) NOT NULL ,
5 [ ParentDeptID ] [ bigint ] NOT NULL
6 ) ON [ PRIMARY ]
7 GO
8
9 INSERT INTO [ SSIP-SSO ] . [ dbo ] . [ Dept ]
10 VALUES
11 ( 1 , ' 集团 ' , 0 ),
12 ( 2 , ' 总公司 ' , 1 ),
13 ( 3 , ' 技术部 ' , 2 ),
14 ( 4 , ' 开发组 ' , 3 ),
15 ( 5 , ' 测试部 ' , 3 ),
16 ( 6 , ' 财务部 ' , 2 ),
17 ( 7 , ' 分公司 ' , 1 ),
18 ( 8 , ' 工程部 ' , 7 ),
19 ( 9 , ' 设备组 ' , 8 ),
20 ( 10 , ' 客服部 ' , 7 )
21 GO
1 ; WITH Dept_Head
2 AS
3 (
4 SELECT DeptID, DeptName, ParentDeptID
5 FROM Dept
6 WHERE DeptName = ' 总公司 '
7 UNION ALL
8 SELECT Dept.DeptID, Dept.DeptName, Dept.ParentDeptID
9 FROM Dept, Dept_Head
10 WHERE Dept.ParentDeptID = Dept_Head.DeptID
11 )
12 Select * FROM Dept_Head
1 CREATE TABLE [ NewTest ]
2 (
3 [ StudentID ] [ bigint ] NOT NULL ,
4 [ TestScore ] [ decimal ] ( 4 , 1 ) NOT NULL
5 ) ON [ PRIMARY ]
6 GO
7
8 INSERT INTO [ NewTest ]
9 VALUES ( 100001 , 90 ),
10 ( 100003 , 85.5 ),
11 ( 100004 , 77 ),
12 ( 101001 , 90 ),
13 ( 101002 , 90 ),
14 ( 101003 , 85.5 ),
15 ( 101004 , 88 )
16 GO
1 MERGE Test
2 USING NewTest
3 ON Test.StudentID = NewTest.StudentID
4 WHEN MATCHED -- 记录两表匹配
5 THEN UPDATE SET Test.TestScore = NewTest.TestScore
6 WHEN NOT MATCHED -- 记录在目标表不存在
7 THEN INSERT VALUES (NewTest.StudentID,NewTest.StudentID / 1000 , NewTest.TestScore)
8 WHEN NOT MATCHED BY SOURCE -- 记录在源表中不存在
9 THEN DELETE
10 ;