如何在两个表之间显示空行
Posted
技术标签:
【中文标题】如何在两个表之间显示空行【英文标题】:How to display a null row between 2 tables 【发布时间】:2012-11-07 07:07:49 【问题描述】:在 SQL Server 2000 中使用视图
表1:
id z1 z2 z3 z4 type
--------------------------------------
01A 300 400 300 400 01
2B 300 400 300 500 02
3C 700 600 400 300 01
04A 500 400 800 900 01
05B 400 300 400 300 02
06 150 200 200 150 03
....
表2:
type value1 value2
------------------------------------
01 0 300
01 301 500
02 0 200
02 201 400
03
.....
我想根据 table2 范围选择 table1 行:
table1 的组合-max(Z1, Z2) and max(Z3, Z4)
如果 Max(z1,z2) 范围小于或等于 table2 max(value2) 其中 table1.type = table2.type 如果 Max(z1, z2) 范围小于等于 table2 max(value2) where table1.type = table2.type
如果 z1、z2 范围小于或等于 table2,那么我想显示 z1、z2 行,否则为 null 如果 z3、z4 范围小于或等于 table2 则我想显示 z3、z4 行,否则为 null
预期输出
表1:
id z1 z2 z3 z4 type
--------------------------------------
01A 300 400 300 400 01 ' `Both (z1, z2), (z3, z4) rows are matching with table2 for type 01`
2B 300 400 null null 02 ' (z1, z2) are matching, (z3, z4) rows are not matching with table2 for type 02
3C null null 400 300 01 ' (z1, z2) rows are not matching, (z3, z4) rows are matching with table2 for type 01
04A 500 400 null null 01 ' (z1, z2) rows are matching, (z3, z4) rows are not matching with table2 for type 01
05B 400 300 400 300 02 ' Both (z1, z2), (z3, z4) rows are matching with table2 for type 02
....
目前我正在使用视图,我不想更改为存储过程,因为大多数报表都使用此视图。
如何在sql..中做到这一点?
【问题讨论】:
【参考方案1】:这似乎给出了预期的结果。 (我更喜欢使用 CTE,但您指定的是 2000)。
样本数据:
declare @T1 table (Id varchar(3) not null,z1 int not null,z2 int not null,z3 int not null,z4 int not null,type char(2) not null)
insert into @T1 (id,z1,z2,z3,z4,type) values
('01A',300,400,300,400,'01'),
('2B',300,400,300,500,'02'),
('3C',700,600,400,300,'01'),
('04A',500,400,800,900,'01'),
('05B',400,300,400,300,'02'),
('06',150,200,200,150,'03')
declare @T2 table (type char(2) not null,value1 int not null,value2 int not null)
insert into @T2 (type,value1,value2) values
('01',0,300),
('01',301,500),
('02',0,200),
('02',201,400)
查询:
select
t1.Id,
CASE WHEN t2.type is not null then z1 END as z1,
CASE WHEN t2.type is not null then z2 END as z2,
CASE WHEN t3.type is not null then z3 END as z3,
CASE WHEN t3.type is not null then z4 END as z4,
t1.type
from
@T1 t1
left join
(select type,MAX(value2) as val2 from @T2 group by type) t2
on
t1.type = t2.type and
t1.z1 <= t2.val2 and
t1.z2 <= t2.val2
left join
(select type,MAX(value2) as val2 from @T2 group by type) t3
on
t1.type = t3.type and
t1.z3 <= t3.val2 and
t1.z4 <= t3.val2
where
t2.type is not null or
t3.type is not null
结果:
Id z1 z2 z3 z4 type
---- ----------- ----------- ----------- ----------- ----
01A 300 400 300 400 01
2B 300 400 NULL NULL 02
3C NULL NULL 400 300 01
04A 500 400 NULL NULL 01
05B 400 300 400 300 02
我不确定你的问题标题的相关性是什么,中间的措辞相当混乱,我猜测了最后的WHERE
子句,因为06
行似乎消失了。
【讨论】:
以上是关于如何在两个表之间显示空行的主要内容,如果未能解决你的问题,请参考以下文章