2015-12-23 62 views
3

這是我的數據庫表:遍歷行和計數基於表名

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 

對於顯而易見的原因,我的查詢不工作,任何幫助讚賞!

+0

如果接入載體衍生的表,如'SELECT * FROM(SELECT字段從表,其中1 = 2)derivedTable'然後這是你應該採取的方法。 –

回答

3

你錯過了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 
+1

這將返回100%的所有行 –

+1

啊...我錯過了原始查詢的問題。更新了我的答案。 –

+0

@BrianPressler會不會將總數計入一個變量中,以便它不需要重複計算? –

0

表中的總記錄分配給一個變量。這將防止它需要爲每條記錄重新計算。只有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)