本文介紹了SQL - 總行數(shù)的百分比的處理方法,對(duì)大家解決問題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
我有這個(gè)查詢:
SELECT
Count(*) as Cnt,
Category
FROM [MyDb].[dbo].[MyTable]
group by Category
order by Cnt
它為我提供了每個(gè) Category
中的行數(shù).現(xiàn)在我想添加第三列,它會(huì)給我 Cnt/(此表中的總行數(shù))
.
It gives me count of rows in each Category
. Now I would like to add a third column that would give me Cnt / (total rows in this table)
.
我該怎么做?
推薦答案
你可以用子查詢來做到:
you could do it with a subquery:
SELECT Count(*) as Cnt, Category,
(Cast(Count(*) as real) / cast((SELECT Count(*) FROM [MyDb].[dbo].[MyTable]) as real)) AS [Percentage]
FROM [MyDb].[dbo].[MyTable]
group by Category
order by Cnt
或使用變量:
declare @total real;
select @total = count(*) from [MyDb].[dbo].[MyTable];
SELECT Count(*) as Cnt, Category, (Cast(Count(*) as real) / @total) AS [Percentage]
FROM [MyDb].[dbo].[MyTable]
group by Category
order by Cnt
我在兩個(gè)示例中都將 count(*) 轉(zhuǎn)換為實(shí)數(shù)以避免整數(shù)除法類型問題.
I've cast count(*) as real in both examples to avoid integer-division type issues.
希望這有幫助約翰
這篇關(guān)于SQL - 總行數(shù)的百分比的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請(qǐng)聯(lián)系我們刪除處理,感謝您的支持!