2016-12-06 27 views
0

输入查找每个位置的病例数并相对于分类的计数的理由采取贷款

+---------+--------------------+-----------+ 
| id |  reason  | location | 
+---------+--------------------+-----------+ 
| 1077501 | credit_card  | AZ  | 
| 1077430 | car    | GA  | 
| 1077175 | small_business  | IL  | 
| 1076863 | other    | CA  | 
| 1075358 | other    | OR  | 
| 1075269 | wedding   | AZ  | 
| 1069639 | debt_consolidation | NC  | 
| 1072053 | car    | CA  | 
| 1071795 | small_busines  | CA  | 
+---------+--------------------+-----------+ 

输出应该是

+----------+-------------+-----+----------------+----------+---------+-------+ 
| location | credit_card | car | small_business | other... | wedding | total | 
+----------+-------------+-----+----------------+----------+---------+-------+ 
| AZ  |   1 | 0 |    0 |  0 |  1 |  2 | 
| CA  |   0 | 1 |    1 |  0 |  0 |  2 | 
+----------+-------------+-----+----------------+----------+---------+-------+ 

输出应在上述格式原因为每个位置作为一列。

+0

你尝试过什么?这是一个基本的东西不应该很难。 – Hogan

+0

是的,我已经尝试过,但理由cloumn值应该动态转换为列我只能为少数值。 。 – Manish

+0

下面的答案适用。 –

回答

0

使用轴与动态列

DECLARE @DynamicPivotQuery AS NVARCHAR(MAX) 
DECLARE @ColumnName AS NVARCHAR(MAX) 

--Get distinct values of the PIVOT Column 
SELECT @ColumnName= ISNULL(@ColumnName + ',','') 
    + QUOTENAME(reason) 
FROM (SELECT DISTINCT reason FROM #T) AS Courses 

--Prepare the PIVOT query using the dynamic 
SET @DynamicPivotQuery = 
N'SELECT location, ' + @ColumnName +',Total = ' + REPLACE(@ColumnName,',[', ' + [') +' 
FROM #T 
PIVOT(count(Id) 
     FOR reason IN (' + @ColumnName + ')) AS PVTTable' 
--Execute the Dynamic Pivot Query 
EXEC sp_executesql @DynamicPivotQuery