34,587
社区成员
发帖
与我相关
我的任务
分享
--> 测试数据:[t_Table]
if object_id('[t_Table]') is not null drop table [t_Table]
create table [t_Table](
[Name] varchar(6),
[Date] datetime,
[AA] int,
[BB] varchar(2)
)
insert [t_Table]
select '设备一','2012-05-18',88,'01' union all
select '设备一','2012-05-17',99,'25' union all
select '设备二','2012-05-18',55,'69' union all
select '设备二','2012-05-17',33,'58' union all
select '设备三','2012-05-18',22,'93' union all
select '设备四','2012-05-18',55,'21' union all
select '设备五','2012-05-18',77,'22'
--查询的是 2012-05-18 的数据
select a.Name,isnull(b.AA,0) AA,ISNULL(b.BB,'0') BB
from(
select [Name] from [t_Table])a
left join (
select * from [t_Table] where [Date]='2012-05-18')b
on a.[Name]=b.[Name]
/*
Name AA BB
-----------------
设备一 88 01
设备一 88 01
设备二 55 69
设备二 55 69
设备三 22 93
设备四 55 21
设备五 77 22
*/
--查询的是2012-05-20的数据
select a.Name,isnull(b.AA,0) AA,ISNULL(b.BB,'0') BB
from(
select [Name] from [t_Table])a
left join (
select * from [t_Table] where [Date]='2012-05-20')b
on a.[Name]=b.[Name]
/*
Name AA BB
------------------
设备一 0 0
设备一 0 0
设备二 0 0
设备二 0 0
设备三 0 0
设备四 0 0
设备五 0 0
*/
select a.name,isnull(aa,0) as aa,isnull(bb,'0') as bb
from
(select distinct name from t_table) a
left join t_table b on a.name=b.name
and b.date='2012-05-20'