我有一张示例表:
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查询获得结果?提前谢谢..
答案 0 :(得分: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
答案 1 :(得分: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;
这会给你:
| 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);