通过比较不同的行和相同的列从表中获取数据

时间:2020-04-19 00:41:37

标签: sql sql-server

对于具有相同公司和区域列的每一行,如果投资价值之一为零,则获取投资价值不为零的行。

对于具有相同“公司”和“区域列”的每一行,如果“投资”值相同,则获取其True_False值为零的行。

这里是完整的查询,可以很好地获取所需的输出。

create table #tempData(
  Company varchar(max), 
  Area varchar(max),
  investment int, 
  True_False Bit
)

insert into #tempData values('Apple','CA', 5244, 0)
insert into #tempData values('Apple','CA', 5244, 1)
insert into #tempData values('Apple','GA', 5244, 0)
insert into #tempData values('Apple','GA', 0, 1)
insert into #tempData values('HP','NC', 100, 0)
insert into #tempData values('HP','NC', 100, 1)
insert into #tempData values('Lenovo','MN', 0, 0)
insert into #tempData values('Lenovo','MN', 0, 1)
insert into #tempData values('Acer','MN', 0, 0)
insert into #tempData values('Acer','MN', 278, 1)


select * into #tempResult1 from (
  select *, DENSE_RANK() over(order by Company, Area) as Rank_  
  from #tempData  
) a 
where a.True_False = 0

select * into #tempResult2 from (
  select *, DENSE_RANK() over(order by Company, Area) as Rank_  
  from #tempData  
) a where a.True_False= 1

select * 
from  #tempResult1 R1 
join #tempResult2 R2 on R1.Rank_ = R2.Rank_

然后:

select  R1.* 
from #tempResult1 R1  
join #tempResult2 R2 on R1.Rank_= R2.Rank_  
where R1.investment = R2.Investment 
  and (R1.investment <> 0 or R2.investment <> 0)
union -- UNION 
select R2.* 
from #tempResult1 R1  
join #tempResult2 R2 on R1.Rank_= R2.Rank_  
where R1.investment = 0 and R2.investment <> 0
union -- UNION
select  R1.* 
from #tempResult1 R1  
join #tempResult2 R2 on R1.Rank_ = R2.Rank_  
where R2.investment = 0 and R1.investment <> 0
union - UNION --
select R1.* 
from #tempResult1 R1  
join #tempResult2 R2 on R1.Rank_ = R2.Rank_  
where R2.investment = 0 and R1.investment = 0

--drop table #tempData
--drop table #tempResult1 
--drop table #tempResult2

现在的问题是,我想在不使用两个临时表#tempResult1和#tempResult2的情况下实现相同的输出。

我尝试了此操作,但不起作用

select * from #tempData t 
 where exists ( select 1 from #tempData t2 where t.Company= t2.Company and t.Area = t2.Area and t.investment =0 and t2.investment <>0  and t2.True_False = 1 )

 union

 select * from #tempData t 
 where exists ( select 1 from #tempData t2 where t.Company= t2.Company and t.Area = t2.Area and t.investment = t2.investment  and t.True_False = 0 )

谢谢。

0 个答案:

没有答案