SQL中的枢轴结构

时间:2013-07-29 12:21:30

标签: sql sql-server sql-server-2008 pivot

我需要一个sql查询来填充一个关键结构中的数据,假设我将下面的表作为示例,我需要在SQL Server 2008中进行查询

ID|EMAIL|Name|Region|Catergory
1|a@a.com|A|AMERICA|PP 
2|b@b.com|B|EMEA|CC 
3|c@c.com|C|APAC|PP 
4|d@d.com|D|APAC|DD 
5|E@c.com|E|EMEA|CC 
6|E@d.com|ED|UNKNOW|CC 

有没有办法获得下面的枢轴结构表,     以下是我希望从上表中计算的结果,

Category|AMERICAS|EMEA|APAC|UNKNOW 

PP|1|0|0|0 
CC|0|2|0 
DD|0|0|1|0 

2 个答案:

答案 0 :(得分:4)

SELECT *
FROM
(
  SELECT id, Catergory, region
  FROM table1
) AS t
PIVOT
(
  COUNT(ID)
  FOR Region IN([AMERICAS],
                [EMEA],
                [APAC],
                [UNKNOW])
) AS p;

DECLARE @cols AS NVARCHAR(MAX);
DECLARE @query AS NVARCHAR(MAX);


select @cols = STUFF((SELECT distinct ',' +
                        QUOTENAME(Region)
                      FROM table1
                      FOR XML PATH(''), TYPE
                     ).value('.', 'NVARCHAR(MAX)') 
                        , 1, 1, '');

SELECT @query = 'SELECT *
FROM
(
  SELECT id, Catergory, region
  FROM table1
) AS t
PIVOT
(
  COUNT(ID)
  FOR Region IN(' + @cols + ')) AS p;';

execute(@query);

答案 1 :(得分:1)

试试这个 -

DECLARE @temp TABLE
(
     ID INT, 
     Name CHAR(2), 
     Region VARCHAR(10), 
     Catergory CHAR(2)
)

INSERT INTO @temp (ID, Name, Region, Catergory)
VALUES 
     (1, 'A', 'AMERICA', 'PP'), 
     (2, 'B', 'EMEA', 'CC'), 
     (3, 'C', 'APAC', 'PP'), 
     (4, 'D', 'APAC', 'DD'), 
     (5, 'E', 'EMEA', 'CC'), 
     (6, 'ED', 'UNKNOW', 'CC')

SELECT *
FROM (
     SELECT Name, Region, Catergory 
     FROM @temp
) src
PIVOT (
     COUNT(Name) 
     FOR Region IN (AMERICAS, EMEA, APAC, UNKNOW)
) pvt

输出 -

Catergory AMERICAS    EMEA        APAC        UNKNOW
--------- ----------- ----------- ----------- -----------
CC        0           2           0           1
DD        0           0           1           0
PP        0           0           1           0