如何在MySQL中查询四分位数1,2和3?

时间:2017-07-09 00:15:20

标签: mysql sql

我有这样的四分位数查询:

cast(substring_index(substring_index(group_concat(`lulusanmagisterrangkuman`.`IPK` 
    order by `lulusanmagisterrangkuman`.`IPK` ASC separator ','),',',(((50 / 100) * count(0)) + 1)),',',-(1)) as decimal(10,0)) AS `Median`,
cast(substring_index(substring_index(group_concat(`lulusanmagisterrangkuman`.`IPK` 
    order by `lulusanmagisterrangkuman`.`IPK` ASC separator ','),',',(((25 / 100) * count(0)) + 1)),',',-(1)) as decimal(10,0)) AS `Q1`,
cast(substring_index(substring_index(group_concat(`lulusanmagisterrangkuman`.`IPK` 
    order by `lulusanmagisterrangkuman`.`IPK` ASC separator ','),',',(((75 / 100) * count(0)) + 1)),',',-(1)) as decimal(10,0)) AS `Q3`

但是这个源代码不适用于浮动值。当我尝试这些代码时,返回的值是一个整数。我可以做什么,以便可以在整数或浮点值中看到四分位数?提前致谢

1 个答案:

答案 0 :(得分:1)

怎么样: 您将值转换为decimal(10,0) - 小数的定义精度为10位数,但刻度为零。 看看这里:Precision & Scale in MySQL 我在下面的陈述中将它们更改为decimal(18,8)

此外,您不需要(50 / 100)之类的内容 - 只需使用0.50

cast(substring_index(
        substring_index(
            group_concat(`lulusanmagisterrangkuman`.`IPK` 
                          order by `lulusanmagisterrangkuman`.`IPK` 
                          ASC separator ','
                        ),',',((0.50 * count(0)) + 1)
                       ),',',-(1)
                    ) as decimal(18,8)
    ) AS `Median`,
cast(substring_index(
        substring_index(
            group_concat(`lulusanmagisterrangkuman`.`IPK` 
                          order by `lulusanmagisterrangkuman`.`IPK` 
                          ASC separator ','
                        ),',',((0.25 * count(0)) + 1)
                       ),',',-(1)
                     ) as decimal(18,8)
    ) AS `Q1`,
cast(substring_index(
        substring_index(
            group_concat(`lulusanmagisterrangkuman`.`IPK` 
                          order by `lulusanmagisterrangkuman`.`IPK` 
                          ASC separator ','
                        ),',',((0.75 * count(0)) + 1)
                       ),',',-(1)
                    ) as decimal(18,8)
    ) AS `Q3`