Search code examples
sqlsql-servert-sqlunionunion-all

Alternative to union all in SQL Server


I want to write the below query without using union all. The only difference in both the queries are for 'Event' and 'Time1' columns:


Solution

  • You can use something like this:

    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)
    

    By the way, you should always define the length of varchar.