选择2个查询的左侧或右侧中的较大者

时间:2012-09-03 10:09:21

标签: sql tsql

我有以下联合查询,查询列的最新日期(如果存在):

SELECT TOP 1 m.sentdate AS 'calltreelastsignedoff' 
FROM Incidents i 
INNER JOIN Plans p ON i.planuid = p.uid 
INNER JOIN IncidentMessages im ON i.uid = im.incidentuid 
INNER JOIN Messages m ON im.messageuid = m.uid 
WHERE p.uid = '031E3346-2921-426E-9494-1111111111' 
UNION
SELECT TOP 1 m.sentdate AS 'calltreelastsignedoff' 
FROM Incidents i
INNER JOIN PlanExercises pe ON i.planexerciseuid = pe.uid
INNER JOIN IncidentMessages im ON i.uid = im.incidentuid 
INNER JOIN Messages m ON im.messageuid = m.uid 
WHERE pe.planuid = '031E3346-2921-426E-9494-1111111111' 

如果每个查询返回前1个结果,则返回2个值。

我真正想要的是选择合并查询的前1位。

如何对联合查询执行选择?

1 个答案:

答案 0 :(得分:3)

试试这个:

您可以使用派生表

执行此操作
select top 1 from
(   
  SELECT TOP 1 m.sentdate AS 'calltreelastsignedoff' 
  FROM Incidents i 
  INNER JOIN Plans p ON i.planuid = p.uid 
  INNER JOIN IncidentMessages im ON i.uid = im.incidentuid 
  INNER JOIN Messages m ON im.messageuid = m.uid 
  WHERE p.uid = '031E3346-2921-426E-9494-1111111111' 

  UNION

  SELECT TOP 1 m.sentdate AS 'calltreelastsignedoff' 
  FROM Incidents i
  INNER JOIN PlanExercises pe ON i.planexerciseuid = pe.uid
  INNER JOIN IncidentMessages im ON i.uid = im.incidentuid 
  INNER JOIN Messages m ON im.messageuid = m.uid 
  WHERE pe.planuid = '031E3346-2921-426E-9494-1111111111' 
)a
order by <col>