반응형

/*******************************************************************************************************************
-- Title : [SQL2016] 통계 추출 - 중위수, 표준편차, Q1, Q3
-- Reference : raresql.com/2013/09/21
-- Key word : 분석 함수 통계 함수 표준 편차 중위수 중앙값 중간값 q1, q3 median stdev percentile_cont 
*******************************************************************************************************************/

-- SQL

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
use tempdb;
go
 
-- # 테이블 & 데이터 생성
create table ttt
( product int
, cost numeric(10,4)
);
 
insert into ttt
select 707, 12.0278 union all
select 707, 13.8782 union all
select 707, 13.0863 union all
select 707, 11.0115 union all
select 708, 13.0863 union all
select 711, 12.0278 union all
select 711, 13.8782 union all
select 711, 13.0863 union all
select 711, 11.0456 union all
select 711, 12.0863 union all
select 712, 5.7052 union all
select 712, 5.2297 union all
select 712, 6.9223 union all
select 713, 23.0807 union all
select 713, 38.4923;
 
select * from ttt;
 
-- # Q1, Q3, Median 생성
select product 
     , percentile_cont(0.25) within group (order by cost) over (partition by product) "Q1"
     , percentile_cont(0.5) within group (order by cost) over (partition by product) "Median"
     , percentile_cont(0.75) within group (order by cost) over (partition by product) "Q3"
from ttt
order by product;
 
 
-- # Product 별 그룹핑
select product
     , count(*) "Product Count"
     , max(q1) "Q1", max(median) "Median", max(q3) "Q3"
     , ISNULL(ROUND(STDEV(cost), 2), 0) "Stdev"
from 
(
    select product, cost
         , percentile_cont(0.25) within group (order by cost) over (partition by product) "Q1"
         , percentile_cont(0.5) within group (order by cost) over (partition by product) "Median"
         , percentile_cont(0.75) within group (order by cost) over (partition by product) "Q3"
    from ttt
) a
group by product
order by product;
cs

 

 

반응형

+ Recent posts