如何在select表达式中返回多个值

时间:2018-03-16 15:57:17

标签: sql sql-server sql-server-2016

我需要返回前十个计划但是一列,HostName可以返回该计划的多个值。如果我与Top 10进行标准联接,我会在某些情况下返回,少于10个计划,但总共10个记录,因为计划可能有多个HostName相关。我希望返回的总记录不受限制,同时确保只返回10个不同的ScheduleId。

这是我的有缺陷的代码,如果计划只有一个HostName,但如果多个则中断,则可以正常工作。

SELECT TOP 10
            s.Id AS ScheduleId
        , s.GroupName
        , a.Id AS AppId
        , a.AppName
        , (SELECT HostName FROM PatchingTargets
            LEFT JOIN ScheduleTargets st on st.ScheduleId = s.Id
            WHERE st.ScheduleId = s.Id) AS HostName
FROM ScheduleTickets t
    LEFT JOIN Schedules s ON s.Id = t.ScheduleId
    LEFT JOIN Applications a ON a.Id = s.AppId
WHERE PatchSessionId = 19 AND CollectionId IS NUll
ORDER BY a.PatchingPriority, s.Idx

这是典型的连接,它总是返回10行但不是所有的HostNames。

SELECT TOP 10
            s.Id AS ScheduleId
        , s.GroupName
        , a.Id AS AppId
        , a.AppName
        ,p.HostName
FROM ScheduleTickets t
    LEFT JOIN Schedules s ON s.Id = t.ScheduleId
    LEFT JOIN ScheduleTargets st on st.ScheduleId = s.Id
    LEFT JOIN dbo.PatchingTargets p on p.Id = st.PatchingTargetId
    LEFT JOIN Applications a ON a.Id = s.AppId
WHERE PatchSessionId = 19 AND CollectionId IS NUll
ORDER BY a.PatchingPriority, s.Idx

没有HostNames的结果,需要添加: enter image description here

这是糟糕的结果: enter image description here

这是我的工作解决方案,可能不优雅,但似乎有效:

SELECT    s.Id AS ScheduleId
        , s.GroupName
        , a.Id AS AppId
        , a.AppName
        ,p.HostName
FROM ScheduleTickets t
    LEFT JOIN Schedules s ON s.Id = t.ScheduleId
    LEFT JOIN ScheduleTargets st on st.ScheduleId = s.Id
    LEFT JOIN dbo.PatchingTargets p on p.Id = st.PatchingTargetId
    LEFT JOIN SchwabApplications a ON a.Id = s.AppId
WHERE PatchSessionId = 19 AND SCCMCollectionId IS NUll
    AND s.Id IN (
        SELECT TOP 10 s.Id AS ScheduleId 
        FROM ScheduleTickets t
            LEFT JOIN Schedules s ON s.Id = t.ScheduleId
            LEFT JOIN SchwabApplications a ON a.Id = s.AppId
        WHERE t.PatchSessionId = 19 AND t.SCCMCollectionId IS NUll
        ORDER BY a.PatchingPriority, s.Idx
    )
ORDER BY a.PatchingPriority, s.Idx

1 个答案:

答案 0 :(得分:0)

如果您希望子查询中最多匹配10个匹配的主机名,则可以使用outer apply

SELECT s.Id AS ScheduleId, s.GroupName, a.Id AS AppId, a.AppName
       ps.HostName
FROM ScheduleTickets t LEFT JOIN
     Schedules s
     ON s.Id = t.ScheduleId LEFT JOIN
     Applications a
     ON a.Id = s.AppId OUTER APPLY
     (SELECT TOP (10) HostName
      FROM PatchingTargets JOIN
           ScheduleTargets st 
           ON st.ScheduleId = s.Id
      WHERE st.ScheduleId = s.Id
     ) ps
WHERE PatchSessionId = 19 AND CollectionId IS NUll
ORDER BY a.PatchingPriority, s.Idx