在我看来,这可能是您从以下代码开始的一个很好的挑战:
Declare @T Table (
MediaID BigInt Primary Key Identity(1, 1)
, MediaTypeID BigInt
, MediaTitle Nvarchar(50)
, MediaDate DateTime
);
Insert @T (
MediaTypeID
, MediaTitle
, MediaDate
) Select 1
, 'Funny Cat Video'
, '2006-01-25 00:00:00.000'
Union
Select 1
, 'Funny Dog Video'
, '2006-01-20 00:00:00.000'
Union
Select 2
, 'Angry Birds Game'
, '2006-03-13 00:00:00.000'
Union
Select 4
, 'Blonde Joke'
, '2006-03-16 00:00:00.000'
Union
Select 3
, 'Goofy Clown Picture'
, '2006-02-27 00:00:00.000'
Union
Select 2
, 'Racing Game'
, '2006-02-10 00:00:00.000'
Union
Select 1
, 'Star Wars Video'
, '2006-07-15 00:00:00.000'
;
Select Month.Title
, Count(Type01_Result.MediaID) As MediaTypeID_1
, Count(Type02_Result.MediaID) As MediaTypeID_2
, Count(Type03_Result.MediaID) As MediaTypeID_3
, Count(Type04_Result.MediaID) As MediaTypeID_4
From (
Select 1 As Id
, 'Jan' As Title
Union
Select 2
, 'Feb'
Union
Select 3
, 'March'
Union
Select 4
, 'April'
Union
Select 5
, 'May'
Union
Select 6
, 'June'
Union
Select 7
, 'July'
Union
Select 8
, 'Aug'
Union
Select 9
, 'Sept'
Union
Select 10
, 'Nov'
Union
Select 11
, 'Oct'
Union
Select 12
, 'Dec'
) As Month
Left Outer Join
@T As Type01_Result
On Type01_Result.MediaTypeID = 1
And DatePart(Month, Type01_Result.MediaDate) = Month.Id
Left Outer Join
@T As Type02_Result
On Type02_Result.MediaTypeID = 2
And DatePart(Month, Type02_Result.MediaDate) = Month.Id
Left Outer Join
@T As Type03_Result
On Type03_Result.MediaTypeID = 3
And DatePart(Month, Type03_Result.MediaDate) = Month.Id
Left Outer Join
@T As Type04_Result
On Type04_Result.MediaTypeID = 4
And DatePart(Month, Type04_Result.MediaDate) = Month.Id
Group By Month.Title
;
唯一的事情是您应该注意年份值以及要在输出中包含多少年,因为无论记录日期是哪一年,此结果都会为您提供每个月所有记录的总和。这可能会导致结果有些混乱。
(记住我在Management Studio的Options中总是将tab size设置为8个字符,所以我建议你这样做看看正确的T-SQL编写方式)
希望它可以帮助你。
干杯