![](/img/trans.png)
[英]Return all distinct values for one column including null, and then count based on a condition
[英]How to generate a table with one row for each count of distinct possibilities from one column, including null?
進行另一次編輯后,這里是一個新標題和一個新范圍,並保留了舊標題。
取這個樣本數據...
('1', 'male'),
('2', 'female'),
('3', 'other'),
('4', 'male'),
('5', 'female'),
('6', 'male'),
('7', null);
然后把它變成這個...
gender cnt
female 2
male 3
null 1
other 1
這是預編輯...
我使用PIVOT
生成一個表,該表包含基於不同行值的動態生成的列名。
這是一些示例數據...
CREATE TABLE #tmp ([id] varchar(5), [gender] varchar(10));
INSERT INTO #tmp
([id], [gender])
VALUES
('1', 'male'),
('2', 'female'),
('3', 'other'),
('4', 'male'),
('5', 'female'),
('6', 'male'),
('7', null);
這是生成結果表的代碼(使用SQL Server(PIVOT)中的“將行值轉換為列”中的一些代碼,以及如何計算SQL Server中的多列? )
---Using Dynamic Pivot
DECLARE @cols AS NVARCHAR(MAX), @query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ',' + QUOTENAME(gender)
from #tmp FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')
set @query = 'SELECT count(*) as cnt,' + @cols + '
from
(
Select id, gender
from #tmp
) dta
pivot
(
MAX(gender)
for gender in (' + @cols + ')
) pvt
group by ' + @cols
execute(@query);
產生以下...
cnt female male other
1 NULL NULL NULL
1 NULL NULL other
3 NULL male NULL
2 female NULL NULL
由此,我想(動態地-不能顯式指定列名'null','other','female','male'等)產生以下內容...
gender cnt
null 1
other 2
male 3
female 2
除了產生最終結果之外,對我來說棘手的部分是獲取“空”行,因為沒有對應的結果列名為“空”。 我從再次使用UNPIVOT
或PIVOT
的角度進行了嘗試。 所以問題是,如何根據我的數據透視和計數結果生成最終結果表? 有沒有一種更簡單,更有效的方法呢?
我不確定我到底是什么問題...為什么不使用Count and group? 真的不需要旋轉/取消旋轉(我認為)
select gender, count(*) as cnt from #tmp group by gender
希望能有所幫助嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.