此方法仅在每种类型都有很多行时才有效
q1min 是第一季度的最小值(总最小值)
q2min 是第二个季度(第一个四分位数)的最小值
q3max 是第三季度(第三四分位数)的最大值
q4max 是第四季度的最大值(总最大值)
declare @my_table table (vertical varchar(50),[Defects(F)] int, [Defects(NF)] int);
insert into @my_table values ('Billing',193,678);
insert into @my_table values ('Provi',200,906);
insert into @my_table values ('Billing',232,111);
insert into @my_table values ('Analyt',67,0);
insert into @my_table values ('Provi',121,690);
insert into @my_table values ('Billing',111,678);
insert into @my_table values ('Billing',111,678);
insert into @my_table values ('Billing',111,678);
insert into @my_table values ('Billing',111,678);
insert into @my_table values ('Billing',111,678);
insert into @my_table values ('Billing',111,678);
insert into @my_table values ('Billing',111,678);
WITH cte as (
select
vertical,
[Defects(F)]+[Defects(NF)] as defects
from @my_table
),
PivotData AS
(
select
vertical,
CASE WHEN quartile in (1,2) THEN MIN(defects) ELSE MAX(defects) END m,
quartile
from (
select
vertical,
defects,
ntile(4) over (PARTITION BY vertical order by defects) as quartile
from cte
) i
group by vertical, quartile
)
select vertical, [1] as q1min, [2] as q2min, [3] as q3max, [4] as q4max
FROM PivotData
PIVOT (SUM(m) FOR quartile in ([1],[2],[3],[4])) as p;