在Postgres获得4位小数

时间:2016-01-19 19:23:22

标签: sql postgresql

我有以下查询,我正试图运行:

SELECT questionid,
       (SUM(CASE WHEN correct = FALSE THEN 1 ELSE 0 END)::decimal(10,4) / COUNT(*)::decimal(10,4))::decimal(10,4) AS PercentWrong,
       COUNT(questionid) AS Questions
FROM asmt.testscores
WHERE testscoreid IN (SELECT DISTINCT test_score_id
                      FROM ads.fbs_assessment_adaptive_pause_staging)
AND   answered = TRUE
AND   memberid IS NOT NULL
GROUP BY questionid
ORDER BY PercentWrong

我希望列PercentWrong有4个小数位,但上面的查询只给了我2个小数位,尽管有decimal(10,4)。我也尝试使用real,但它根本没给我小数位。

如何获得4位小数?

1 个答案:

答案 0 :(得分:2)

尝试使用to_char

SELECT questionid,
       to_char(SUM(CASE WHEN correct = FALSE THEN 1 ELSE 0 END)::float / COUNT(*)::float,'99D9999') AS PercentWrong,
       COUNT(questionid) AS Questions
FROM asmt.testscores
WHERE testscoreid IN (SELECT DISTINCT test_score_id
                      FROM ads.fbs_assessment_adaptive_pause_staging)
AND   answered = TRUE
AND   memberid IS NOT NULL
GROUP BY questionid
ORDER BY PercentWrong