2017-04-25 46 views
1

我正在製作一個視圖。我現在擁有的是:加入視圖T-SQL

CREATE VIEW [dbo].[vwEventDetails] 
AS 
SELECT 
    ISNULL(ROW_NUMBER() OVER (ORDER BY EventID), 999999999) AS Row, 
    STUFF(DetectorID, len(DetectorID), 1, '0') as SiteID, 
    DetectorID AS DetectorID, 
    StartedOn AS StartedOn, 
    EndedOn AS EndedON, 
    EventDescription AS EventDescription, 
    EventCategoryID AS EventCategoryID, 
    EventSeverityLevelID AS EventSeverityLevelID, 
    EventStatusID AS EventStatusID, 
    Processed AS Processed, 
    CASE WHEN EndedOn IS NOT NULL 
     THEN 
      DATEDIFF(SECOND, StartedOn, EndedOn)/ 3600.0 
     ELSE 
      DATEDIFF(SECOND, StartedOn, CURRENT_TIMESTAMP)/ 3600.0 
    END 
     AS Duration 

FROM Event 

GO 

,我從這個觀點得到我的結果是: View Result

我得到的結果是正確的。但是,我需要1個更多的值,這不在事件表中。我不知道如何獲得這個價值。

該視圖基於事件表。它看起來像這樣:

Event Table

現在,在這個表中有一個名爲DetectorID行。
DetectorID導致表:探測器

Detector Table

在這個表格中,你將看到一個名爲的TrackID行。
的TrackID導致表軌道

Track Table

在表中有一個名爲TRACKNAME行。
這是我想要的視圖中的值。 有沒有辦法做到這一點?

所以基本上是一個簡短的總結。 有沒有辦法從去:

事件 - 通過它基於事件視圖>軌道

- >探測器?

回答

1

在sql中加入其他表是一個相當標準的事情。

您可以使用inner join只返回行,其中存在匹配的DetectorTrack,或者你可以使用left join時有可能無法在相應的表格中匹配的值。

另外,row_number()將不會返回null,沒有理由在isnull()包裝。

--create view dbo.vwEventDetails as 
select 
    row_number() over (order by e.EventId) as Row 
    , stuff(DetectorId, len(e.DetectorId), 1, '0') as SiteId 
    , e.DetectorId 
    , e.StartedO 
    , e.EndedOn 
    , e.EventDescription 
    , e.EventCategoryId 
    , e.EventSeverityLevelId 
    , e.EventStatusId 
    , e.Processed 
    , case when e.EndedOn is not null 
     then datediff(second, e.StartedOn, e.EndedOn)/ 3600.0 
     else datediff(second, e.StartedOn, current_timestamp)/ 3600.0 
     end as Duration 
    , t.TrackId 
    , t.FromName 
    , t.ToName 
    , t.TrackName 
from Event e 
    inner join Detector d 
    on e.DetectorId = d.DetectorId 
    inner join Track t 
    on d.TrackId = t.TrackId 
+0

謝謝,這是行得通的!我對聯接瞭解不多,並不知道如何在多個表上進行聯接。並且在一個視圖中。但非常感謝你! – Mitch

+1

@Mitch樂意幫忙! – SqlZim

1

你可以用兩個連接語句做到這一點:

... 
FROM Event 
JOIN Detector ON Event.DetectorID = Detector.DetectorID 
JOIN Track ON Detector.DetectorID = Track.TrackID 

然後加入Track.TrackName到選擇字段

結束(你有你等領域,其中前添加Event.有同名的列)