這可能很長,我很抱歉,我可以得到「羅嗦」,試圖解釋我自己。沒有學會像我應該那樣簡潔。SQL Server查詢幫助將表格佈局中的行拉出糾結
我的問題是,我由於缺乏經驗和我認爲是擺放不好的桌子而受阻。我需要從表格中拉出某些列並報告嵌入其中一個元素的日期差異。 (請參閱下面的示例)。
我無法重組表格,因爲它是我的公司在幫助臺上使用的應用程序的一部分,所以我堅持如何「組織」。
表的結構基本上是這樣的:所有的列類型不同長度的VARCHAR(),該數據庫是在Windows Server上的SQL Server 2005 2003
tickID | tickGen | tickAudit
----------------------------------
124567 | 1 | 2011-07-22 08:00:00 joeuser Open Ticket
124567 | 2 | 2011-07-22 08:00:00 joeuser Open Ticket Not Assigned
124567 | 3 | 2011-07-22 08:00:00 joeuser Open Ticket Priority Urgent
124567 | 4 | 2011-07-22 09:00:00 freduser Open Ticket Add Assignee
管理想知道之間的時間差這些從「joeuser」使票據「未分配」並且「freduser」向票證添加受理人時起tickAudit列中的「時間戳記」。
在這個例子中,我想出了這些查詢該「之類的作品,」但我相信可以做得更好:
declare @startTime datetime
declare @endTime datetime
declare @mrid varchar(6)
set @mrid = '124567'
select @startTime = cast(substring(tickAudit,1,19) as datetime)
from tickHistory where tickID = @tickID and tickAudit like '%Not Assigned'
select @endTime = cast(substring(tickAudit,1,19) as datetime)
from tickHistory where tickID = @tickID and tickAudit like '%Add Assignee'
select @mrid as 'ticket', @startTime as 'startTime',
@endTime as 'endTime', datediff(mi,@startTime,@endTime) as 'diff'
查詢但不能處理的問題,即一個「票」有多個條目的地方被分配再未分配如下例所示:
tickID | tickGen | tickAudit
----------------------------------
124568 | 1 | 2011-07-22 08:00:00 joeuser Open Ticket
124568 | 2 | 2011-07-22 08:00:00 joeuser Open Ticket Not Assigned
124568 | 3 | 2011-07-22 08:00:00 joeuser Open Ticket Priority Urgent
124568 | 4 | 2011-07-22 09:00:00 freduser Open Ticket Add Assignee
124568 | 5 | 2011-07-22 11:00:00 freduser Open Ticket Not Assigned
124568 | 6 | 2011-07-22 12:00:00 bobuser Open Ticket Priority Low
124568 | 7 | 2011-07-22 12:00:00 bobuser Open Ticket Add Assignee
這裏的「freduser」編輯了票,現在則是「未分配」了兩小時後「bobuser」有編輯和分配門票。所以我需要報告2個時間戳。我的查詢只會返回tickGen#5和tickGen#7的區別。它忽略了tickGen#2和tickGen#4的差異。或者我懷疑它只顯示查詢的最後一個有效匹配,無論返回多少個匹配。
這就是我卡住的地方。希望有人能給我一些建議或例子來解釋上述例子中的情況。