CREATE TABLE [T]
(
CreatedOn DATETIME NOT NULL
,Name NVARCHAR(20) NOT NULL
,Code NVARCHAR(20) NOT NULL
,R FLOAT NULL
,C1 FLOAT NULL
,C2 FLOAT NULL
,C3 FLOAT NULL
);
INSERT INTO [T] VALUES
('2013-01-01', N'A', N'', 13, NULL, NULL, NULL)
,('2013-01-07', N'A', N'1', NULL, 5, NULL, NULL)
,('2013-01-31', N'A', N'2', NULL, 4, NULL, NULL)
,('2013-02-01', N'A', N'1', NULL, NULL, 6, NULL)
,('2013-02-15', N'A', N'2', NULL, NULL, NULL, 3)
,('2013-03-01', N'A', N'1', NULL, 1, NULL, NULL)
,('2013-03-05', N'A', N'', 8, NULL, NULL, NULL)
,('2013-03-22', N'A', N'2', NULL, NULL, NULL, 1)
,('2013-05-01', N'A', N'1', NULL, 2, NULL, NULL);
In [T]
1. One and only one non-null value per row for [R], [C1], [C2] and [C3]
2. [Code] contains a non-empty value if [C1], [C2] or [C3] contains a non-null value
3. There is an index on [Name]
4. Contains millions of rows
5. Few unique values of [Code], typically less than 100
6. Few unique values of [Name], typically less than 10000
7. Is actually a complex view containing several inner joins
如何从 [T] ([DateMonth], [P]) 中选择 [CreatedOn] >= @Start AND [CreatedOn] <= @End AND [Name] = @Name AND [P] = Sum([R] ) - (Sum(MaxOf(Sum([C1]), Sum([C2]), Sum([C3]), per unique [Code])))?(有关更准确的“解释”,请参阅下面的预期输出。)@Start - @End 每个月的结果集中都应该有一行,无论 [T] 中是否有该月的行。临时表使用是可以接受的。
Expected Output
@Name = N'A'
@Start = '2012-12-01'
@End = '2013-07-01'
DateMonth P
'2012-12-01' 0
'2013-01-01' 4 -- 4 = SUM([R])=13 - (MaxForCode'1'(SUM(C1)=5, SUM(C2)=0, SUM(C3)=0)=5 + MaxForCode'2'(SUM(C1)=4, SUM(C2)=0, SUM(C3)=0)=4)
'2013-02-01' 3 -- 3 = SUM([R])=13 - (MaxForCode'1'(SUM(C1)=5, SUM(C2)=6, SUM(C3)=0)=6 + MaxForCode'2'(SUM(C1)=4, SUM(C2)=0, SUM(C3)=3)=4)
'2013-03-01' 11 -- 11 = SUM([R])=13+8=21 - (MaxForCode'1'(SUM(C1)=5+1=6, SUM(C2)=6, SUM(C3)=0)=6 + MaxForCode'2'(SUM(C1)=4, SUM(C2)=0, SUM(C3)=3+1=4)=4)
'2013-04-01' 11
'2013-05-01' 9 -- 9 = SUM([R])=13+8=21 - (MaxForCode'1'(SUM(C1)=5+1=6, SUM(C2)=6+2=8, SUM(C3)=0)=8 + MaxForCode'2'(SUM(C1)=4, SUM(C2)=0, SUM(C3)=3+1=4)=4)
'2013-06-01' 9
'2013-07-01' 9