0

我有以下查询:

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'

然后我可以从视图中检索它。

现在,我不确定如何对以下内容进行类似操作,在这种情况下,我需要将其放入交叉连接中,类似于我上面的操作。

请注意实际日期是如何更复杂的。我需要像上面那样使用交叉表,但不是如您所见,它涉及更多。

(注意这部分,我将简单地加入我上面与 UNION 的 view1

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'

然后我可以从视图中检索它。

4

1 回答 1

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。结果是一个子查询,其中包含对外部级别表的引用。这样的子查询称为相关子查询。

于 2012-08-10T13:53:17.350 回答