[英]Loop through rows and count based on table name
這是我的數據庫表:
Status
------
Active
Active
Inactive
Removed
Removed
我想要的輸出:
Status | Total | Percent
-------------------------------
Active | 2 | 33.33
Inactive | 1 | 16.66
Removed | 3 | 50
Total | 6 | 100
我嘗試過的:
SELECT
OrderStatus AS Status,
COUNT(OrderStatus) AS Total,
ROUND(((COUNT(OrderStatus ) * 100)/COUNT(*)),2) AS Percent
FROM
myTable
由於顯而易見的原因,我的查詢無效,任何幫助表示贊賞!
您缺少group by子句,您需要除以記錄的總數,您可以使用子查詢獲得這些記錄:
SELECT
OrderStatus AS Status,
COUNT(OrderStatus) AS Total,
ROUND((COUNT(OrderStatus ) * 100)/(select COUNT(*) from myTable),2) AS [Percent]
FROM
myTable
Group by OrderStatus
將表中的總記錄分配給變量。 這將防止需要為每條記錄重新計算它。 只有5條記錄的小問題,但如果您將此邏輯應用於具有更多唯一值的更大表,則差異應該變得顯着。
SQL:
declare @TempTable table([OrderStatus] varchar(50))
insert into @TempTable
values
('Active'),
('Active'),
('Inactive'),
('Removed'),
('Removed')
DECLARE @TotalRecords int = (Select Count(*) from @TempTable)
SELECT
OrderStatus AS Status,
COUNT(OrderStatus) AS Total,
ROUND((COUNT(OrderStatus ) * 100)/@TotalRecords,2) AS [Percent]
FROM
@TempTable
Group by OrderStatus
結果:
(5 row(s) affected)
Status Total Percent
-------------------------------------------------- ----------- -----------
Active 2 40
Inactive 1 20
Removed 2 40
(3 row(s) affected)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.