2012-08-10 88 views
0

我有以下查詢:的SQL Server交叉聯接

select 
    tt.ItemOrder, tt.DisplayVal as Task, tt.Responsible as ResParty, 
    tt.DaysDue, 
    ActualDate = (select convert(varchar(10), cnfmdate, 101) from ProSer where PId = @PID), PDate = @PDate 
from 
    tblTimeline tt 
where 
    tt.ID = 1 

我需要做的就是把它放在一個觀點,這樣我可以調用簡單地使用PID的看法。 我想出了以下內容並使用交叉連接:

create view view1 as 
    select 
     ps.PID, tt.ID, tt.ItemOrder, tt.DisplayVal as Task, 
     tt.Responsible as ResParty, tt.DaysDue, 
     ps.cnfmdate As ActualDate, ProgStartDate as ProgramDate 
    from 
     tblTimeline tt 
    cross join 
     ProSer ps 
    where 
     tt.ID = 1 and ps.cancelled = 0 

注意,現在,我可以做以下

select * 
from view1 
where PID = '34343' 

,然後我可以從視圖中檢索。

現在,我不知道如何做到與以下情況類似,在這種情況下,我需要將它與交叉連接放在一起,類似於上面的操作。

請注意實際日期是如何涉及更多的一些。我需要使用交叉表,類似於上面的操作,但不像您所看到的那樣,它涉及更多。

(注意這個部分,我將simly加入到我與UNION上面有廠景

select 
    tt.ItemOrder, tt.DisplayVal as Task, tt.Responsible as ResParty, 
    ActualDate = (
      CASE 
      WHEN 
      NOT EXISTS(SELECT * FROM Spls WHERE RequestRcvd = 1 AND PID = @PID) 
      THEN 
      'N/A'  
      WHEN EXISTS (SELECT * FROM spls WHERE RequestRcvd = 1 AND RequestRcvdDate IS NOT NULL) 
      THEN 
      (SELECT CONVERT(VARCHAR(10),MAX(RequestRcvdDate),101) from spls WHERE RequestRcvd = 1 AND PID = @PID) 
      END 
     ) 
from 
    tblTimeline tt 
where 
    tt.ID = 9 

我需要知道我可以創建這個在交叉連接(這將是一個內部視圖),這樣我可以做類似下面的如何,我做了一個以上

select * 
from view1 
where PID = '34343' 

,然後我可以從視圖中檢索。

+0

proser是否包含您想要查詢的PID? – 2012-08-10 13:36:45

+0

是的,proser確實包含PID – 2012-08-10 13:40:11

回答

0

有可能是簡化查詢的方式,但以下應該工作:

select p.pid, tt.ItemOrder, tt.DisplayVal as Task, 
     tt.Responsible as ResParty, 
     ActualDate = (CASE WHEN NOT EXISTS(SELECT * FROM Spls WHERE RequestRcvd = 1 AND spls.PID = p.PID) 
          THEN 'N/A' 
          WHEN EXISTS (SELECT * FROM spls WHERE RequestRcvd = 1 AND RequestRcvdDate IS NOT NULL) 
          THEN (SELECT CONVERT(VARCHAR(10),MAX(RequestRcvdDate),101) from spls WHERE RequestRcvd = 1 AND spls.PID = p.PID) 
        END) 
from tblTimeline tt cross join 
    poser p 
where tt.ID = 9 

我所做的只是將交叉連接添加到poser並用p.pid替換@PID。結果是包含對外部表的引用的子查詢。這種子查詢稱爲相關子查詢。