Sql server 基于原始表中未使用的列,在轴之后添加计算列
考虑到本表:Sql server 基于原始表中未使用的列,在轴之后添加计算列,sql-server,datetime,sum,pivot,cout,Sql Server,Datetime,Sum,Pivot,Cout,考虑到本表: 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
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 |
如何修改pivot查询,以便获得另一列,其中包含每个名称的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)*100
按Name
分组,使用条件聚合更容易:
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
选择
名称
总和(当日期>='20200101'和日期<'20200201'时,则将其计算为0结束)作为计数,
总和(当日期>='20200201'和日期<'20200301'时,则将其计数为0结束)作为计数,
合计(日期>='20200301'和日期<'20200401'时的情况,然后将其他0结束计数)作为计数
100.0*总和(计数失败)/总和(计数)失败百分比
从mytable
按名称分组
考虑使用交叉制表符而不是限制性的PIVOT
运算符,这将容易得多。我假设这将对每个count\u xxx列的所有表行执行case
条件验证?我正在尽可能地提高查询的性能。这是最有效的(至少与pivot
解决方案一样有效)。(日期、计数)
上的索引可能有助于加快查询速度。