首页 > 解决方案 > 在 SQL Server 中联合所有的替代方案

问题描述

我想在不使用 union all 的情况下编写以下查询。两个查询的唯一区别是 for'Event''Time1'columns:

标签: sqlsql-servertsqlunionsunion-all

解决方案


你可以使用这样的东西:

Select  L.id
,       L.StudentID
,       L.Name
,       L.Owner
,       O.Stage
,       O.probab
,       Multiplier.Event as Event
,       Multiplier.Time1
From    Lead L 
CROSS APPLY (
                VALUES  ('Lead', case when L.converted='true' and convert(varchar,L.ldate,23)<>convert(varchar,O.odate,23) then O.date else L.date end)
                ,       ('Contact Attempt', case when L.Attempted is null then O.Attempted else L.ContactAttempted end)
            ) AS Multiplier(Event, Time1)
left join Opp O
        ON O.LeadID=L.LeadID
left join Acc A 
        ON A.id=O.AccountId
left join zip Z 
        ON z.CODE = left(L.postalcode,5)
where (L.ldate is not null or o.NewAssigned is not null)

顺便说一句,您应该始终定义varchar.


推荐阅读