-1

我在下面有一个示例表:

FACE   SHAP
----   ----
new1   oblq
new2   oblq
new3   rond
new5   sqre
new2   rond
new1   oblq
new2   oblq
new3   rond
new2   rond
new3   oblq

我希望它像这样显示:

FACE   oblq   rond   sqre
----   ----   ----   ----
new1      2      0      0
new2      2      2      0
new3      2      2      0
new5      0      0      1

如何使用 SQL 查询获得结果?提前致谢..

4

2 回答 2

1

使用以下代码:

select FACE,
       SUM(Case When SHAP = 'oblq' then 1 Else 0 End )AS oblq,
       SUM(Case When SHAP = 'rond' then 1 Else 0 End )AS rond,
       SUM(Case When SHAP = 'sqre' then 1 Else 0 End )AS sqre
From yourTable
Group by FACE
于 2013-03-04T07:05:08.220 回答
1

使用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;

SQL 小提琴演示

这会给你:

| 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);

更新的 SQL Fiddle 演示

于 2013-03-04T07:07:41.880 回答