1

我在 MSSQL 2008 R2 数据库中有大约 300 万个数据点的表结构。

vertical|Defects(F)|Defects(NF)|
--------------------------------
Billing |193       |678
Provi   |200       |906
Billing |232       |111
Analyt  |67        |0
Provi   |121       |690

我需要计算最小值、最大值、第一四分位数和第三四分位数来绘制晶须图。因此希望以以下格式输出

vertical|Max       |Min      |Q1       |Q3
--------------------------------
Billing |343       |24       |103.75   |263.25
Provi   |811       |110      |285.25   |635.75
Analyt  |67        |67       |67       |67

请注意,最大、最小和四分位数的计算是在添加缺陷(F)和缺陷(NF)之后完成的

请帮忙!!

4

1 回答 1

1

此方法仅在每种类型都有很多行时才有效

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;
于 2013-06-13T15:24:20.533 回答