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

问题描述

考虑此表:

in

以及以下数据透视查询:

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),'2020-02-12',4,1),'2020-02-13','2020-03-21','2020-03-25',('B',6,3),3,10,4),('C',1,11,('D',7,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],[03])
) as pivotTable

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

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

原始查询中根本没有使用| 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 | 列,而最后一列并不关心数据透视表,只是CountFailedSUM(CountFailed) / SUM(Count) * 100分组了。

解决方法

使用条件聚合更容易做到

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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...