根据原始 table 中未使用的列,在数据透视表后添加计算列

Adding a calculated column after a pivot, based on an unused column from the original table

考虑到这一点table:

create table #tmptmp ([Name] nvarchar(1), [Date] datetime2, [Count] int, [CountFailed] int);

insert into #tmptmp values
('A', '2020-01-03', 8, 2),
('A', '2020-01-05', 2, 0),
('A', '2020-02-12', 4, 1),
('A', '2020-02-13', 4, 1),
('A', '2020-03-21', 2, 1),
('A', '2020-03-25', 8, 1),

('B', '2020-01-03', 6, 3),
('B', '2020-01-05', 6, 1),
('B', '2020-02-12', 3, 0),
('B', '2020-02-13', 4, 0),
('B', '2020-03-21', 10, 4),
('B', '2020-03-25', 8, 1),

('C', '2020-01-03', 8, 3),
('C', '2020-01-05', 1, 1),
('C', '2020-02-12', 11, 0),
('C', '2020-02-13', 4, 0),
('C', '2020-03-21', 2, 0),

('D', '2020-01-03', 11, 0),
('D', '2020-01-05', 8, 0),
('D', '2020-02-12', 7, 0),
('D', '2020-02-13', 8, 1),
('D', '2020-03-21', 10, 0),
('D', '2020-03-25', 1, 0);

以及以下数据透视查询:

SELECT [Name], [01], [02], [03] from
(
    SELECT [Name], FORMAT([Date], 'MM') as [NumMonth], SUM([Count]) as [Total] from #tmptmp
    group by FORMAT([Date], 'MM'), [Name]
) t
PIVOT
(
    SUM([Total])
    FOR [NumMonth] in ([01], [02], [03])
) as pivotTable

我得到了这个结果集:

|  Name   | Jan. | Feb. | Mar. |
|    A    |  10  |   8  |  10  |
|    B    |  12  |   7  |  18  |
|    C    |   9  |  15  |   2  |
|    D    |  19  |  15  |  11  |

如何修改数据透视表查询,以便我可以获得另一个包含每个名称的 CountFailed 百分比的列?

|  Name   | Jan. | Feb. | Mar. | % Failed |
|    A    |  10  |   8  |  10  |   21.42  |
|    B    |  12  |   7  |  18  |   24.32  |
|    C    |   9  |  15  |   2  |   15.38  |
|    D    |  19  |  15  |  11  |    2.22  |

原始查询中根本没有使用 CountFailed 列,最后一列不关心主元,它只是 SUM(CountFailed) / SUM(Count) * 100Name 分组。

条件聚合更容易完成:

select 
    name,
    sum(case when date >= '20200101' and date < '20200201' then count else 0 end) as count_jan,
    sum(case when date >= '20200201' and date < '20200301' then count else 0 end) as count_fev,
    sum(case when date >= '20200301' and date < '20200401' then count else 0 end) as count_mar
    100.0 * sum(countfailed) / sum(count) failed_percent
from mytable
group by name