答案 0 :(得分:0)
如果我正确地读取您的示例数据,那么似乎对于Query3,您可以为日期翻转数据。我认为在2017年10月20日过去的Query3应该是2:03,对于10/21/2017,经过的时间应该是1:48。
如果确实如此,这是一个使用Common Table Expressions,聚合和PIVOT组合的解决方案。它适用于您在问题中提供的示例数据。您可能需要针对其他数据进行调整。
set nocount on
Declare @t Table (ID int, [Date] Date, ExecutedTime varchar(10), Label Varchar(10))
insert into @t values
(1,'2017-10-20','0:01:16','Query1'),
(2,'2017-10-20','0:00:20','Query1'),
(3,'2017-10-20','0:00:14','Query1'),
(4,'2017-10-20','0:01:43','Query2'),
(5,'2017-10-20','0:00:33','Query2'),
(6,'2017-10-20','0:00:34','Query2'),
(7,'2017-10-20','0:01:18','Query3'),
(8,'2017-10-20','0:00:30','Query3'),
(9,'2017-10-20','0:00:15','Query3'),
(10,'2017-10-21','0:01:16','Query1'),
(11,'2017-10-21','0:00:20','Query1'),
(12,'2017-10-21','0:00:14','Query1'),
(13,'2017-10-21','0:01:43','Query2'),
(14,'2017-10-21','0:00:33','Query2'),
(15,'2017-10-21','0:00:34','Query2'),
(16,'2017-10-21','0:01:18','Query3'),
(16,'2017-10-21','0:00:30','Query3')
;
With ExecutedTimeInSeconds as --Convert ExecutedTime to seconds in preparation for aggregation
(
select
[Date],
Label,
datepart(hour,(convert(time,executedTime))) * 3600 +
datepart(minute,(convert(time,executedTime))) * 60 +
datepart(second,(convert(time,executedTime))) as ElapsedSeconds
from @t
)
,AggregatedDataInElapsedSeconds as --Aggregate the seconds by Date and Label
(
SELECT [Date]
,Label
,sum(ElapsedSeconds) AS ElapsedSeconds
FROM ExecutedTimeInSeconds
GROUP BY [Date]
,Label
),
DataReadyForPivot as --Convert the aggregageted seconds back to an elapsed time
(
SELECT [Date], Label,
RIGHT('0' + CAST(ElapsedSeconds / 3600 AS VARCHAR),2) + ':' +
RIGHT('0' + CAST((ElapsedSeconds / 60) % 60 AS VARCHAR),2) + ':' +
RIGHT('0' + CAST(ElapsedSeconds % 60 AS VARCHAR),2) as ExecutedSum
from AggregatedDataInElapsedSeconds
)
,
PivotedData as --Pivot the data
(
SELECT *
FROM DataReadyForPivot
PIVOT(MAX(ExecutedSum) FOR Label IN (
[Query1]
,[Query2]
,[Query3]
)) AS pvt
)
select --add a row number as Id
ROW_NUMBER() over (order by [Date] desc) as Id,
*
from PivotedData
| Id | Date | Query1 | Query2 | Query3 |
|----|------------|----------|----------|----------|
| 1 | 2017-10-21 | 00:01:50 | 00:02:50 | 00:01:48 |
| 2 | 2017-10-20 | 00:01:50 | 00:02:50 | 00:02:03 |