2015-05-07 89 views
4

請參閱下面的DDL:SQL語句來生成列的值

create table Person (ID int, [Type] int) 
insert into Person values (1,1) 
insert into Person values (2,1) 
insert into Person values (3,2) 
insert into Person values (4,3) 
insert into Person values (5,4) 
insert into Person values (6,5) 

我在尋找這樣一個結果:

2 1 1 1 1 

以下標準產生這樣的結果:

There are 2 persons with a type of 1 (The first column value is: 2) 
There is 1 person with a type of 2 (The second column value is: 1) 
There is 1 person with a type of 3 (The third column value is: 1) 
There is 1 person with a type of 4 (The forth column value is: 1) 
There is 1 person with a type of 5 (The fifth column value is: 1) 
+2

I T嗨,你問的是一個PIVOT查詢。 – Randy

+1

類型限制爲5個選項還是n?如果n然後http://stackoverflow.com/questions/10404348/sql-server-dynamic-pivot-query如果有限,那麼你不必使用動態SQL和下面的情況下工作或標準的樞紐。 – xQbert

回答

6

使用CASESUM不同類型的

select sum(case when [Type] = 1 then 1 else 0 end), 
     sum(case when [Type] = 2 then 1 else 0 end), 
     sum(case when [Type] = 3 then 1 else 0 end), 
     sum(case when [Type] = 4 then 1 else 0 end), 
     sum(case when [Type] = 5 then 1 else 0 end) 
from tablename 
1

如果您希望info_message的通用性不如它的轉換爲只有1個計數,那麼我可以這樣做,但這需要我不認爲必要的案例邏輯。這取決於你。只要讓我知道你是否想讓我改變它。

DECLARE @Cnt_list VARCHAR(MAX) = 
            (
            SELECT CAST(COUNT(*) AS VARCHAR(10)) + ' ' 
            FROM Person 
            GROUP BY [Type] 
            ORDER BY [Type] 
            FOR XML PATH('') 
            ) 
SELECT @Cnt_list as cnt_list 

結果:

cnt_list 
---------- 
2 1 1 1 1 

然後,對於第二部分:

SELECT 'There are ' + CAST(COUNT(*) AS VARCHAR(10)) + ' person(s) with a type of ' + CAST([type] AS VARCHAR(10)) + '(The first column value is: ' + CAST(COUNT(*) AS VARCHAR(10)) + ')' info_message 
FROM Person 
GROUP BY [Type] 

結果:

info_message 
-------------------------------------------------------------------- 
There are 2 person(s) with a type of 1(The first column value is: 2) 
There are 1 person(s) with a type of 2(The first column value is: 1) 
There are 1 person(s) with a type of 3(The first column value is: 1) 
There are 1 person(s) with a type of 4(The first column value is: 1) 
There are 1 person(s) with a type of 5(The first column value is: 1) 
+0

你可以用STUFF函數代替varchar(max)來去除xml標籤,'SELECT STUFF((''**你的語句在這裏**'),1,1,''))' –

+0

是的,我以前用過xml的東西,但是我不確定OP想要什麼,所以我認爲變量是最通用的。 – Stephan