我的表格包含以下值id
和amt
id amt amt%
1 500 16.7
2 600 20
3 900 30
4 1000 33.3
-----------------------------
3000 100%
我必须通过将amt%
除以id=1
来找到amt
的{{1}}。
如何在sql中编写查询?
答案 0 :(得分:2)
select id, amt, 100.0 * amt / (select sum(amt) from tab) as amt_percent
from tab
注意100.0
,.0
非常重要,它会“强制”将int
转换为float
s。
添加:
select t.id, t.amt, 100.0 * t.amt / p.s as amt_percent
from tab t
join (
select id, sum(amt) as s
from tab
group by id
) p on p.id = t.id
和替代方式:
select id, amt,
100.0 * amt / (
select sum(amt)
from tab t1
where t1.id = t.id
) as amt_percent
from tab t
我更喜欢加入子查询 - 第一个。
答案 1 :(得分:1)
select id, amt, 100*amt/(select NULLIF(sum(amt),0) from tbl) as "amt%"
from tbl
或者可能是
select t.id, t.amt, 100*amt/sm.s as "amt%"
from tbl t, (select NULLIF(sum(amt),0) as s from tbl) sm
修改检查除以零
答案 2 :(得分:1)
您可以尝试这样的事情:
SELECT
id, amt,
amt / (SELECT SUM(amt) FROM tabl) * 100 as amtperc
FROM tabl
答案 3 :(得分:1)
假设您使用的是Oracle(如上一个问题所述),请尝试:
select id, amt, 100 * amt / sum(amt) over () amtperc
from your_table
答案 4 :(得分:0)
select id, amt, 100 * amt/(case when (select sum(amt)as ss from tablename)>0 then
(select sum(amt)as ss from tablename) else 1 end) as [amt%] from tablename