我有一个场景。以下是我的3张桌子:
create table #cdes(client_id int,identifier int)
insert #cdes values(9908,789654123)
create table #temp1
(
client_id int,
identifier int,
pp_id int,
ch_id int,
code varchar(20),
program varchar(20),
startdate date,
enddate date,
ssc varchar(50)
)
insert into #temp1
values (9908,789654123,1567,1566,'OP','xASMT','1/1/2019','1/4/2019','A201901044F010134NNN01D 151 143 093 ')
-------------------------------------------
create table #temp2
(
client_id int,
identifier int,
pp_id int,
ch_id int,
code varchar(20),
program varchar(20),
startdate date,
enddate date,
ssc varchar(20)
)
insert into #temp2
values(9908,789654123,1574,1573,'OP','SU1','1/1/2019','1/4/2019',NULL)
我的最终选择查询中有一个案例条件,因为我的查询围绕多个条件展开。大多数案例条件只将一行输出作为输出,但是,我想针对特定场景报告多行。
我想要的输出:
我的查询:
select
d.client_id,
case when d.client_id = 9908
then
(
select CONCAT(t1.code,t1.startdate,t1.enddate,t1.ssc)
from #temp1 t1
left join #temp2 t2 on t1.client_id = t2.client_id and t1.identifier = t2.identifier
union all
select CONCAT(t2.code,t2.startdate,t2.enddate,t2.ssc)
from #temp1 t1
left join #temp2 t2 on t1.client_id = t2.client_id and t1.identifier = t2.identifier)
end
from #cdes d
left join #temp1 t1 on d.client_id = t1.client_id
left join #temp2 t2 on d.client_id = t2.client_id
问题是Unionall正在产生大量行,我发现很难在我的select语句中容纳这些行。有帮助吗?!
这种情况是假的。我只是提供了一个示例。
答案 0 :(得分:1)
不要在子查询中放入UNION ALL查询。使您的整个查询成为UNION ALL查询。
代替:
SELECT ColA, ColB, (
SELECT CalculationX FROM MyTable
UNION ALL
SELECT CalculationY FROM MyTable
) AS ColC
FROM MyTable
您需要这样的东西:
SELECT ColA, ColB, CalculationX AS ColC FROM MyTable
UNION ALL
SELECT ColA, ColB, CalculationY AS ColC FROM MyTable
答案 1 :(得分:1)
您已经有了子查询,因此只需在where
之后添加条件:
select t.* from (
select t1.client_id client_id, t1.identifier identifier, CONCAT(t1.code,t1.startdate,t1.enddate,t1.ssc) ssc_concatenated
from #temp1 t1
union all
select t2.client_id client_id, t2.identifier identifier, CONCAT(t2.code,t2.startdate,t2.enddate,t2.ssc) ssc_concatenated
from #temp2 t2) t
where t.client_id in (select client_id from #cdes)
或
where t.client_id = 9908
或者您可以直接在子查询的每个部分中添加条件:
select t.* from (
select t1.client_id client_id, t1.identifier identifier, CONCAT(t1.code,t1.startdate,t1.enddate,t1.ssc) ssc_concatenated
from #temp1 t1
where t1.client_id = 9908
union all
select t2.client_id client_id, t2.identifier identifier, CONCAT(t2.code,t2.startdate,t2.enddate,t2.ssc) ssc_concatenated
from #temp2 t2
where t2.client_id = 9908