我做了一個計算資料并回傳帖子數量的查詢,我將它放入 INTO 變數中,如下所示:
declare
cnt_posts int;
begin
select count(*) as cnt into cnt_posts from posts;
/*for exapmle this will return 300*/
end;
/
所以我想在其他查詢中使用這個變數內的結果,如下所示:
其他查詢:
select posts.id, round(100*(count(my_data) / sum(:cnt_posts) over()),2) as percentage
from posts
where posts.category_id = 3
group by posts.id
所以我想在其他查詢中使用 cnt_posts 來計算百分比
uj5u.com熱心網友回復:
使用系結變數:
VARIABLE cnt_posts NUMBER;
BEGIN
SELECT count(*)
INTO :cnt_posts
FROM posts;
END;
/
select posts.id,
round(
100*count(my_data)/:cnt_posts,
2
) as percentage
from posts
where posts.category_id = 3
group by posts.id
然后,在 SQL Developer 中,使用F5.
或者,您可以將其全部合并到一個查詢中:
select posts.id,
round(
100*count(my_data)/(SELECT COUNT(*) FROM posts),
2
) as percentage
from posts
where posts.category_id = 3
group by posts.id
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/532680.html
標籤:甲骨文oracle11goracle-sqldeveloper
上一篇:查詢查找不按順序排列的計數器
