Ich habe die folgende Tabelle zum Pivotieren.
Tabelle :
CREATE TABLE Emp_Month
(
EMPID int,
[Month] varchar(10)
);
Einfügung :
INSERT INTO Emp_Month VALUES(101,'July');
INSERT INTO Emp_Month VALUES(102,'June');
INSERT INTO Emp_Month VALUES(103,'May');
INSERT INTO Emp_Month VALUES(104,'April');
INSERT INTO Emp_Month VALUES(105,'March');
INSERT INTO Emp_Month VALUES(201,'July');
INSERT INTO Emp_Month VALUES(202,'July');
INSERT INTO Emp_Month VALUES(203,'June');
INSERT INTO Emp_Month VALUES(204,'July');
INSERT INTO Emp_Month VALUES(205,'June');
INSERT INTO Emp_Month VALUES(301,'January');
INSERT INTO Emp_Month VALUES(302,'January');
INSERT INTO Emp_Month VALUES(303,'February');
INSERT INTO Emp_Month VALUES(304,'February');
INSERT INTO Emp_Month VALUES(305,'February');
Erwartete Ausgabe : Ich möchte die COUNT(last_months_from_current_date) drucken
Last_6_Month Last_5_Month Last_4_Month Last_3_Month Last_2_Month Last_1_Month
--------------------------------------------------------------------------------------------
13 10 9 8 7 4
Mein Versuch :
select *
from
(
SELECT t.Month,t.[Month] as Mon
FROM Emp_Month t
) src
pivot
(
COUNT(Mon)
for [Month] in ([Last_6_Month],[Last_5_Month],[Last_4_Month],[Last_3_Month],[Last_2_Month],[Last_1_Month])
) piv;
Aber alle Nullwerte bekommen.
Nun, das hat mir ein bisschen den Kopf verdreht. Aber das wird tun, was Sie verlangen.
Was Ihnen fehlt, ist, dass Sie für eine laufende Summe eine Möglichkeit haben müssen, Ihr Set zu bestellen. Hier wird also gebaut, um eine Monatsnummer zu bekommen. Es ist nicht das Beste, aber es funktioniert für das Beispiel.
Nach dem Gruppieren und der laufenden Summe ist ein Pivot etwas übertrieben, aber Sie haben nach einem gefragt und hier geht es. Ich hoffe es hilft.
(*Ich habe einige Änderungen an der akzeptierten Antwort vorgenommen, damit sich die Spaltenüberschriften des Pivots selbst aktualisieren. Andernfalls müssten Sie dies jeden Monat ändern.)
;WITH
MonthsCountedOrdered AS
(
SELECT count(EMPID) empCount, Month, Datediff(M, [Month] + ' 1, 2017', getdate()) + 1 monthsPast
FROM Emp_Month
GROUP BY [Month]
)
, RunningTotal AS
(
SELECT
Month
, SUM(empCount) OVER (Order By monthsPast ROWS UNBOUNDED PRECEDING) tot
, 'Last_' + cast(monthsPast as varchar(2)) + '_Month' as ColumnHeader
FROM
MonthsCountedOrdered
WHERE
monthsPast <= 6
)
SELECT *
FROM
(
SELECT t.ColumnHeader,t.tot
FROM RunningTotal t
) src
pivot
(
Sum(tot)
for [ColumnHeader] in (Last_6_Month,Last_5_Month,Last_4_Month,Last_3_Month,Last_2_Month,Last_1_Month)
) piv;
Ergebnis:
Last_6_Month Last_5_Month Last_4_Month Last_3_Month Last_2_Month Last_1_Month
------------ ------------ ------------ ------------ ------------ ------------
13 10 9 8 7 4
Dieser Artikel stammt aus dem Internet. Bitte geben Sie beim Nachdruck die Quelle an.
Bei Verstößen wenden Sie sich bitte [email protected] Löschen.
Lass mich ein paar Worte sagen