如何在以下查询中添加百分比列?我想在第四列中显示相应的(升级/ needsupgrade * 100),但这会返回" 0"在"百分比"柱:
SELECT
upgraded,
needsupgrade,
total,
upgraded / needsupgrade * 100 AS 'percent done'
FROM
(
SELECT count(id) AS upgraded
FROM attempts
WHERE needsupgrade = 1
) upgraded,
(
SELECT count(id) AS needsupgrade
FROM attempts
WHERE needsupgrade = 0
) needsupgrade,
(
SELECT count(id) AS total
FROM attempts
) total
答案 0 :(得分:2)
这可能是由于SQL Server在对整数进行分割时返回一个整数 在你的情况下,这可能是0,你需要将至少一个字段转换为十进制。
SELECT
upgraded,
needsupgrade,
total,
(upgraded / convert(decimal, needsupgrade)) * 100 AS 'percent done'
FROM
(
SELECT count(id) AS upgraded
FROM attempts
WHERE needsupgrade = 1
) upgraded,
(
SELECT count(id) AS needsupgrade
FROM attempts
WHERE needsupgrade = 0
) needsupgrade,
(
SELECT count(id) AS total
FROM attempts
) total
答案 1 :(得分:1)
int除以和int将返回一个int
只需为计算添加一些精度
(upgraded / (needsupgrade+0.0)) * 100 AS 'percent done'
例如
Select 25/100 Returns 0
While
Select 25/(100+.0) Returns 0.25