我在SQL Server 2008中有两个临时表
表1,results_types
------------
| Result_1 |
| Result_2 |
| Result_3 |
| Result_N |
------------
表2,all_results
--------------------
| Run_A | Result_1 |
| Run_A | Result_2 |
| Run_B | Result_3 |
| Run_B | Result_3 |
| Run_B | Result_3 |
| Run_B | Result_3 |
| Run_C | Result_2 |
--------------------
如何创建一个返回摘要的查询,该摘要统计* results_types *中的每个条目,而不需要遍历* results_types *。 提前致谢
-----------------------------------------------------
| 'Run' | Result_1 | Result_2 | Result_3 | Result_N |
-----------------------------------------------------
| Run_A | 1 | 2 | 0 | 0 |
| Run_B | 0 | 0 | 4 | 0 |
| Run_C | 0 | 2 | 0 | 0 |
-----------------------------------------------------
答案 0 :(得分:2)
您可以使用SQL-server Pivot函数和动态SQL:
DECLARE @Cols NVARCHAR(MAX) = STUFF(( SELECT ',' + Result_Type
FROM Result_Types
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)'), 1, 1, '');
DECLARE @SQL NVARCHAR(MAX) = ' SELECT *
FROM all_results
PIVOT
( COUNT(Result_Type)
FOR Result_Type IN (' + @Cols + ')
) pvt;'
EXECUTE SP_EXECUTESQL @SQL;
<强> Example on SQL Fiddle 强>