将sql行转换为列

时间:2015-08-20 10:38:39

标签: sql sql-server pivot

我有一个非常不寻常的要求。我在表中有一些过滤数据,列是ID,日期和事件。 Event是一个XML列,其中一个标签是StartWork和EndWork。从大量数据中我过滤掉了请求的数据。我的Sample数据有6行,按StartWork,EndWork,StartWork,EndWork等顺序排列。 我究竟想要做的是找出每种组合之间的时差。 我的意思是,EndWork - StartWork =差异。下一个EndWork - StartWork = Difference2等等。

enter image description here

基本上我想要,2-1,4-3,6-5等等。 我尝试用Pivot做,但无法获得理想的结果

3 个答案:

答案 0 :(得分:2)

Select DateDiff(minute,StartWork.datacreated,EndWork.datacreated)
from 
(Select datacreated,LineNb=row_number() over(Order by datacreated) from Table where eventdata.value('(/data/status/text())[1]','varchar(15)')='StartWork') StartWork
INNER JOIN 
(Select datacreated,LineNb=row_number() over(Order by datacreated) from Table where eventdata.value('(/data/status/text())[1]','varchar(15)')='EndWork') EndWork
ON StartWork.LineNb=EndWork.LineNb

答案 1 :(得分:1)

这可以帮到你:

declare @xmlStart XML='<data><status>StartWork</status></data>';
declare @xmlENd XML='<data><status>EndWork</status></data>';

declare @tbl TABLE(id INT,datecreated DATETIME,eventdata XML);
INSERT INTO @tbl VALUES(1,{ts'2015-07-29 09:17:34'},@xmlStart)
                      ,(2,{ts'2015-07-29 09:20:24'},@xmlEnd)
                      ,(3,{ts'2015-07-29 10:05:41'},@xmlStart)
                      ,(4,{ts'2015-07-29 10:18:34'},@xmlEnd);

WITH resolvedCTE AS
(
    SELECT TOP 100 PERCENT id,datecreated,eventdata.value('(/data/status)[1]','varchar(max)') AS EventStatus FROM @tbl
)
,StartEvnets AS
(
    SELECT ROW_NUMBER() OVER(ORDER BY datecreated) AS inx,id,datecreated FROM resolvedCTE WHERE EventStatus='StartWork' 
)
,EndEvnets AS
(
    SELECT ROW_NUMBER() OVER(ORDER BY datecreated) AS inx,id,datecreated FROM resolvedCTE WHERE EventStatus='EndWork' 
)SELECT StartEvnets.id, CAST(EndEvnets.datecreated - StartEvnets .datecreated AS TIME)
FROM StartEvnets
INNER JOIN EndEvnets ON StartEvnets.inx =EndEvnets.inx 

答案 2 :(得分:0)

假设&#34; tbl&#34;是你的桌名。你走了:

SELECT t.datecreated - t2.datecreated
FROM tbl t, tbl t2
WHERE t.id IN
    (SELECT id FROM tbl WHERE _eventdata LIKE ('%EndWork%'))
    AND t2.id = t.id -1

如果有效,请将其标记为已回答......