create table t (col1 int,col2 varchar(10))
insert into t values(10,'val')
insert into t values(20,null)
insert into t values(10,'val3')
insert into t values(40,'val1')
insert into t values(50,null)
insert into t values(60,'val')
--1.
SELECT *,COUNT(COL2) OVER (ORDER BY COL1) FROM T
--2.
SELECT *,COUNT(COL1) OVER (ORDER BY COL2) FROM T
我无法理解上面提到的两个选择查询的输出..任何人都可以详细说明。
答案 0 :(得分:2)
SELECT *,COUNT(COL2) OVER (ORDER BY COL1) AS [count]
FROM T
ORDER BY COL1
结果:
col1 col2 count --explanation
10 val3 2 --The first two values of col1 are the same, and the values of col2 are not null.
10 val 2 --The first two values of col1 are the same, and the values of col2 are not null.
20 NULL 2 --A new value of col1, but col2 is null so it's not counted.
40 val1 3 --A new value of col1, and col2 is not null.
50 NULL 3 --A new value of col1, but col2 is null so it's not counted.
60 val 4 --A new value of col1, and col2 is not null.
SELECT *,COUNT(COL1) OVER (ORDER BY COL2) As col1Count
FROM T
ORDER BY COL2
结果:
col1 col2 col1Count --explanation
20 NULL 2 --The first two values of col2 are the same (both null), and the values of col1 are not null.
50 NULL 2 --The first two values of col2 are the same (both null), and the values of col1 are not null.
60 val 4 --The next two values of col2 are the same (both 'val'), and the values of col1 are not null.
10 val 4 --The next two values of col2 are the same (both 'val'), and the values of col1 are not null.
40 val1 5 --A new value of col2, and col1 is not null.
10 val3 6 --A new value of col2, and col1 is not null.