数据透视查询聚合函数

时间:2015-07-03 12:21:15

标签: sql-server

我们正在开展一项任务,我们将测试结果存储在数据库中。这是我们的表:

|Path     | Date       | Result   |
|---------------------------------|
|Test1    | 01/01/2015 | True     |
|Test2    | 01/01/2015 | False    |
|Test1    | 02/02/2015 | True     |
|Test2    | 02/02/2015 | False    |

在此表中Path是[varchar],Date是[smalldatetime]和Result [bit]。我们想创建一个数据透视存储过程,它将以下列格式显示数据:

|Path     | [01/01/2015] | [02/02/2015] | [03/03/2015]|
|-----------------------------------------------------|
|Test 1   | True         | True         | True        |
|Test 2   | False        | False        | False       |

到目前为止,我们设法得到所有日期:

SET @sql = 'SELECT * FROM (SELECT [Path],[Date],[Result] FROM [dbo].[Results]) AS 

[SubTable] 
pivot
(
    MAX([Result])
    FOR [Date] IN ([' + @docDates + '])
) AS [Pivot];';

EXEC @sql;

这将选择我们需要的所有测试日期,但重复测试名称。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

抱歉,列名错误。不过这里有什么对我有用:

SELECT * FROM (SELECT [Path], [Date], CAST([Result] as tinyint) as [Result]  FROM [dbo].[Results]) AS [SubTable] PIVOT (Min([Result]) FOR [Date] IN ([01/01/15],[02/02/15],[03/03/15])) AS [Pivot];