Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/86.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ionic-framework/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
SQL Server中union all的替代方案_Sql_Sql Server_Tsql_Unions_Union All - Fatal编程技术网

SQL Server中union all的替代方案

SQL Server中union all的替代方案,sql,sql-server,tsql,unions,union-all,Sql,Sql Server,Tsql,Unions,Union All,我想在不使用union all的情况下编写以下查询。这两种查询的唯一区别在于'Event'和'Time1'列:您可以使用以下内容: Select L.id , L.StudentID , L.Name , L.Owner , O.Stage , O.probab , Multiplier.Event as Event , Multiplier.Time1 From Lead L CROSS APPLY

我想在不使用union all的情况下编写以下查询。这两种查询的唯一区别在于
'Event'
'Time1'
列:

您可以使用以下内容:

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)
选择L.id
,L.StudentID
,L.姓名
,L.业主
,O.舞台
,O.probab
,乘数。事件作为事件
,乘数.Time1
从铅L
交叉应用(
值('Lead',L.converted时的大小写='true'和convert(varchar,L.ldate,23)转换(varchar,O.odate,23)然后是O.date,否则为L.date end)
,('Contact-trunt',当L.trunted为空时,则为O.trunted,否则为L.Contact-trunted结束)
)作为乘数(事件,时间1)
左连接Opp O
ON O.LeadID=L.LeadID
左连接附件A
在A.id=O.AccountId上
左连接zip Z
z.CODE=左侧(L.postalcode,5)
其中(L.ldate不为空或o.NewAssigned不为空)

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

union all
的长度是
union all
尝试不使用特定于此的工具并期望得到相同的结果是不明智的。这也是为什么会出现问题的原因。
union-all
不是很有用吗?我从上面的查询中得到了所需的结果,但在上面的查询的继续部分中,我得到了类似的10个union-all,并且看起来非常麻烦您的union逻辑正在生成新记录。工会是这份工作的正确工具。不,但我认为问题是你一直在使用错误的工具。在两个select子句中使用相同的表(具有完全相同的where条件),我假设您根本不需要使用
union
。但是,您应该使用
案例
来表示
事件
时间1
。非常感谢,这个查询成功了。我刚刚在所有联接之后添加了交叉应用条件