使用PIVOT
表运算符:
SELECT *
FROM
(
SELECT *, ROW_NUMBER()OVER(PARTITION BY Face
ORDER BY Shap) RN
FROM tablename
) AS p
PIVOT
(
COUNT(RN)
FOR SHAP IN(oblq, rond, sqre)
) AS p;
这会给你:
| FACE | OBLQ | ROND | SQRE |
-----------------------------
| new1 | 2 | 0 | 0 |
| new2 | 2 | 2 | 0 |
| new3 | 1 | 2 | 0 |
| new5 | 0 | 0 | 1 |
对于多个值SHAP
并且您不需要手动编写它们,您必须使用动态 SQL 动态地执行此操作。像这样:
DECLARE @cols AS NVARCHAR(MAX);
DECLARE @query AS NVARCHAR(MAX);
select @cols = STUFF((SELECT distinct ',' +
QUOTENAME(SHAP)
FROM tablename
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
, 1, 1, '');
SET @query =
' SELECT *
FROM
(
SELECT *, ROW_NUMBER() OVER(PARTITION BY Face
ORDER BY Shap) RN
FROM tablename
) AS p
PIVOT
(
COUNT(RN)
FOR SHAP IN( ' + @cols + ')
) AS p;';
EXECUTE(@query);