如何在SQL中计算四分位数?

时间:2015-02-12 05:51:19

标签: sql postgresql rows percentile

我正在使用postgresql,我的表有近1000000行:

  CREATE TABLE Data(
  id varchar(8) PRIMARY KEY,
  jan INT,
  feb INT,
  mar INT,
  apr INT,
  may INT,
  jun INT,
  jul INT,
  aug INT,
  sep INT, 
  oct INT,
  nov INT,
  dec INT);

我想获得四分位数

例如:

ID    jan  feb  mar apr may jun jul aug sep oct nov dec
A10    1    2   3    4   5   6   7   8   9  10  11  12

我想输出为:

ID    Q1  Q2  Q3 Q4
A10    3  6   9  12

我怎么能在postgresql中做到这一点?

2 个答案:

答案 0 :(得分:1)

这可能会给你想要的结果:

Select id, 
       jan + feb + mar as Q1,
       apr + may + jun as Q2,
       jul + aug + sep as Q3,
       oct + nov + dec as Q4,
From Data

答案 1 :(得分:0)

您可以添加构成Quarters的列

select id
, (case 
     when jan>feb and jan>mar then jan
     when feb>jan and feb>mar then feb
     else mar END
       ) q1
...Similarly for q2,q3,q4
from table