TSQL-OVER-Klausel: COUNT(*) OVER (ORDER BY a)

Dies ist mein code:

USE [tempdb];
GO

IF OBJECT_ID(N'dbo.t') IS NOT NULL
BEGIN
    DROP TABLE dbo.t
END
GO

CREATE TABLE dbo.t
(
    a NVARCHAR(8),
    b NVARCHAR(8)
);
GO

INSERT t VALUES ('a', 'b');
INSERT t VALUES ('a', 'b');
INSERT t VALUES ('a', 'b');
INSERT t VALUES ('c', 'd');
INSERT t VALUES ('c', 'd');
INSERT t VALUES ('c', 'd');
INSERT t VALUES ('c', 'd');
INSERT t VALUES ('e', NULL);
INSERT t VALUES (NULL, NULL);
INSERT t VALUES (NULL, NULL);
INSERT t VALUES (NULL, NULL);
INSERT t VALUES (NULL, NULL);
GO

SELECT  a, b,
    COUNT(*) OVER (ORDER BY a)
FROM    t;

Auf diese Seite von BOL, Microsoft sagt, dass:

Wenn PARTITION BY nicht angegeben, wird die Funktion behandelt alle Zeilen der
abfrageresultsets als einzelne Gruppe.

Also, basierend auf meinem Verständnis, die letzten SELECT - Anweisung gibt mir das folgende Ergebnis. Da alle Datensätze sind als in einer einzigen Gruppe, richtig?

a        b        
-------- -------- -----------
NULL     NULL     12
NULL     NULL     12
NULL     NULL     12
NULL     NULL     12
a        b        12
a        b        12
a        b        12
c        d        12
c        d        12
c        d        12
c        d        12
e        NULL     12

Aber das tatsächliche Ergebnis ist:

a        b        
-------- -------- -----------
NULL     NULL     4
NULL     NULL     4
NULL     NULL     4
NULL     NULL     4
a        b        7
a        b        7
a        b        7
c        d        11
c        d        11
c        d        11
c        d        11
e        NULL     12

Jemand helfen kann, zu erklären, warum? Danke.

Ich könnte mich irren, aber ich glaube nicht, dass COUNT(*) OVER (ORDER BY-Feld) überhaupt funktioniert...
das meinte ich -- danke...
Es funktioniert in SQL Server 2012 - siehe sqlfiddle.com/#!6/fe2f9/7
Hallo Jungs, wie hieß es in der BOL-Seite, die partition by - Klausel ist optional. "Wenn PARTITION BY nicht angegeben, wird die Funktion behandelt alle Zeilen des abfrageresultsets als einzelne Gruppe".
Danke @MarkBannister -- ich steh Irre...

InformationsquelleAutor Ogrish Man | 2013-02-13

Schreibe einen Kommentar