本文介紹了SQL - 總行數的百分比的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我有這個查詢:
SELECT
Count(*) as Cnt,
Category
FROM [MyDb].[dbo].[MyTable]
group by Category
order by Cnt
它為我提供了每個 Category
中的行數.現在我想添加第三列,它會給我 Cnt/(此表中的總行數)
.
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
我在兩個示例中都將 count(*) 轉換為實數以避免整數除法類型問題.
I've cast count(*) as real in both examples to avoid integer-division type issues.
希望這有幫助約翰
這篇關于SQL - 總行數的百分比的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!