同一行返回多次

时间:2017-09-27 08:40:53

标签: sql-server inner-join union

目前,我在交换机中使用了三个端口,并尝试使用下面的SQL监控流量。

select a.interface, a.utilization_in, b.utilization_out from
(select z.source as interface, y.samplevalue as utilization_in from #TABLE1 z
join #TABLE2 y
on z.table_id = y.table_id
where z.source = 'switch1' and z.port like 'port_in%') a

INNER JOIN

(select x.source as interface, w.samplevalue as utilization_out from #TABLE1 x
join #TABLE2 w 
on x.table_id = w.table_id
where x.source = 'switch1' and x.port like 'port_out%') b
on a.interface=b.interface

这得到了我的结果,但每行重复几次,3 * 3 = 9.我一直在搜索并发现有些人使用了union运算符。但是,我甚至迷失在哪里。感谢

3 个答案:

答案 0 :(得分:0)

union表示您有两个具有相同列数的单独SELECT查询,并且您将两者的结果显示为一个结果集。

所以基本上是这样的:

SELECT ... FROM ... WHERE ...

UNION 

SELECT ... FROM ... WHERE ...

请记住,UNION也会执行distinct,因此不会返回重复的行。如果您不想要不同,请使用UNION ALL

答案 1 :(得分:0)

select z.source as interface, y.samplevalue as utilization_in from #TABLE1 z
join #TABLE2 y
on z.table_id = y.table_id
where z.source = 'switch1' and z.port like 'port_in%'

UNION ALL -- or use just UNION if there are could be duplicates in both parts

select x.source as interface, w.samplevalue as utilization_out from #TABLE1 x
join #TABLE2 w 
on x.table_id = w.table_id
where x.source = 'switch1' and x.port like 'port_out%'

但由于您具有相同的连接条件且唯一的区别在于端口,因此您可以使用以下查询:

select z.source as interface, y.samplevalue as utilization, CASE WHEN z.port like 'port_in%' THEN 'IN' ELSE 'OUT' END as in_or_out
from #TABLE1 z
join #TABLE2 y
on z.table_id = y.table_id
where z.source = 'switch1'

答案 2 :(得分:0)

只需使用条件聚合,这样您只需从表中选择一次:

select x.source as interface, 
       MAX(CASE WHEN x.port like 'port_out%' THEN w.samplevalue END) as utilization_out,
       MAX(CASE WHEN x.port like 'port_in%' THEN w.samplevalue END) as utilization_in
from #TABLE1 x
join #TABLE2 w 
 on x.table_id = w.table_id
where x.source = 'switch1' 
GROUP BY x.source