0

我需要一个 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 
4

2 回答 2

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);
于 2013-07-29T12:23:44.927 回答
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
于 2013-07-29T12:28:50.550 回答