很抱歉,但我无法获得“%”列的2位小数结果。
任何人都可以帮助我吗?
这是查询:
SELECT
"column1"
COUNT("column1"),
COUNT("column1") * 100 / (SELECT COUNT(*) FROM "table") AS "%",
AVG( "column2" )
FROM
"table"
GROUP BY
"column1"
答案 0 :(得分:1)
某些数据库执行整数除法,count()
返回整数。您应该转换为小数点表示。我认为最简单的方法是乘以1.0。此外,您不需要子查询;你可以使用窗口函数:
SELECT "column1", COUNT( "column1" ),
COUNT("column1") * 100.0 / SUM(COUNT(*)) OVER () as percent
AVG("column2")
ROM "table"
GROUP BY "column1";
要获得两位小数,请转换为十进制类型(或字符串,但前者是标准的):
SELECT "column1", COUNT("column1"),
CAST(COUNT("column1") * 100.0 / SUM(COUNT(*)) OVER () as DECIMAL(5, 2)) as percent
AVG("column2")
FROM "table"
GROUP BY "column1";
另请注意,AVG()
遵循与整数除法相同的规则。如果您想要一个带小数位的值,请乘以1.0(或进行显式转换)。