-2

我在 sql 数据库上有以下数据集

 ----------------------------------
|  ID   | NAME    | AGE  | STATUS |
-----------------------------------
| 1ASDF | Brenda  | 21   | Single |
-----------------------------------
| 2FDSH | Ging    | 24   | Married|
-----------------------------------
| 3SDFD | Judie   | 18   | Widow  |
-----------------------------------
| 4GWWX | Sophie  | 21   | Married|
-----------------------------------
| 5JDSI | Mylene  | 24   | Singe  |
-----------------------------------

我想查询该数据集,以便我的结果中有这个结构

--------------------------------------
|  AGE  | SINGLE  | MARRIED  | WIDOW |
--------------------------------------
| 21    | 1        | 1       | 0     |
--------------------------------------
| 24    | 1        | 1       | 0     |
--------------------------------------
| 18    | 0        | 0       | 1     |
--------------------------------------

状态栏可以是动态的,所以会有更多的栏。这可能吗?

4

1 回答 1

1

由于您使用的是 SQL Server,因此可以PIVOT像这样使用表运算符:

SELECT *
FROM 
(
  SELECT Age, Name, Status FROM tablename 
) AS t
PIVOT
(
  COUNT(Name)
  FOR Status IN(Single, Married, Widow)
) AS p;

SQL 小提琴演示


要动态地执行此操作,您必须像这样使用动态 sql:

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


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

SELECT @query = '
SELECT *
FROM 
(
  SELECT Age, Name, Status FROM tablename 
) AS t
PIVOT
(
  COUNT(Name)
  FOR Status IN( ' +@cols + ')
) AS p;';


execute(@query);
于 2013-09-30T10:53:55.653 回答