两个已排序的子查询合并为一个结果

时间:2013-03-25 18:44:44

标签: sql-server database sql-server-2008 tsql

所以我有两个子查询从同一个表中返回相同的列

查询#1:

SELECT E.Id,E.Title,E.LocationId,P.LocationId,E.DepartmentId,P.DepartmentId,E.DateCreated,E.IsActive,E.IsHotJob,E.RequisitionId,E.RequisitionIdString,E.RewardSettingId,E.EmploymentOpportunityStatusId 
FROM EmploymentOpportunities E, Profiles P
WHERE E.EmploymentOpportunityStatusId = 9 AND E.IsActive = 1 AND E.IsHotjob = 1  
     AND P.Id = 'C5F07EBB-CE81-4133-A462-241A5F84D418' AND (P.DepartmentId != E.DepartmentId AND P.LocationId != E.LocationId)
ORDER BY E.DateCreated DESC

查询#2:

SELECT E.Id,E.Title,E.LocationId,P.LocationId,E.DepartmentId,P.DepartmentId,E.DateCreated,E.IsActive,E.IsHotJob,E.RequisitionId,E.RequisitionIdString,E.RewardSettingId,E.EmploymentOpportunityStatusId 
FROM EmploymentOpportunities E, Profiles P
WHERE E.EmploymentOpportunityStatusId = 9 AND E.IsActive = 1 AND E.IsHotjob = 0 AND 
      P.Id = 'C5F07EBB-CE81-4133-A462-241A5F84D418' AND (P.DepartmentId = E.DepartmentId OR P.LocationId = E.LocationId)
ORDER BY E.DateCreated DESC

我希望这两个查询组合成一个但保留它们的顺序,因此以某种方式将查询#1堆叠到查询#2上。

这可能吗?

2 个答案:

答案 0 :(得分:0)

SELECT 1 SetNumber, E.Id,E.Title,E.LocationId,P.LocationId,E.DepartmentId,
  P.DepartmentId,E.DateCreated,E.IsActive,E.IsHotJob,E.RequisitionId,
  E.RequisitionIdString,E.RewardSettingId,E.EmploymentOpportunityStatusId
FROM EmploymentOpportunities E, Profiles P
WHERE E.EmploymentOpportunityStatusId = 9 AND E.IsActive = 1 
  AND E.IsHotjob = 1 P.Id = 'C5F07EBB-CE81-4133-A462-241A5F84D418' 
  AND (P.DepartmentId != E.DepartmentId AND P.LocationId != E.LocationId)

union all

SELECT 2, E.Id,E.Title,E.LocationId,P.LocationId,E.DepartmentId,P.DepartmentId,
  E.DateCreated,E.IsActive,E.IsHotJob,E.RequisitionId,E.RequisitionIdString,
  E.RewardSettingId,E.EmploymentOpportunityStatusId
FROM EmploymentOpportunities E, Profiles P
WHERE E.EmploymentOpportunityStatusId = 9 AND E.IsActive = 1 
  AND E.IsHotjob = 0 AND P.Id = 'C5F07EBB-CE81-4133-A462-241A5F84D418' 
  AND (P.DepartmentId = E.DepartmentId OR P.LocationId = E.LocationId)

ORDER BY SetNumber, DateCreated desc

答案 1 :(得分:0)

只需使用UNION ALL

即可
SELECT * FROM
(
    Your Query1

    UNION ALL      // do not use order by here

    Your Query2 
) AS someName
ORDER BY yourColumn DESC

您也可以使用UNION - 但如果有的话,它会过滤掉重复的内容。