前两天在这里请教了关于数据按时间显示,在表里没有的也要显示出来的问题。得到高手指教十分感谢,但发现里面有一个问题。就是left join后,当表里没有这条数据时,只有时间是有值的,其它都是null的,不知能否解决?具体如下:create table ab
(
城市 varchar(6),
金额 int,
日期 varchar(10)
)
insert into ab
select '广州', '20000', '2012-06-20' union all
select '北京', '30000', '2012-06-20' union all
select '上海', '30000', '2012-06-20' union all
select '广州', '20000', '2012-06-22' union all
select '北京', '30000', '2012-06-22' union all
select '上海', '30000', '2012-06-22' union all
select '广州', '20000', '2012-06-23' union all
select '北京', '30000', '2012-06-23' union all
select '上海', '30000', '2012-06-23'declare @begindate datetime
set @begindate='2012-6-18'
declare @enddate datetime
set @enddate='2012-6-30'create table #datetb
(
DT datetime
)while @begindate<=@enddate
begin
insert into #datetb
select @begindate
set @begindate=@begindate+1
end--查询
select b.城市,isnull(b.金额,0),a.DT 日期
from #datetb as a left join cb as b on a.DT=b.日期运行上面SQL后,得出的结果变成这样了:从结果看出,出现null的行,表示当天所有城市都没有数据的。例如:21号全天所有城市没有交易数据。
现在希望就是把 显示出来的数据也可以显示21号当天三个城市数据为0,而不希望出现null的城市名(实际数据中城市有几十个)。就是说一条null的数据,应该变成n条有城市名称的数据。请大家指教,十分感谢!!城市 金额 日期
广州 20000 2012-06-20
北京 30000 2012-06-20
上海 40000 2012-06-20
广州 0 2012-06-21
北京 0 2012-06-21
上海 0 2012-06-21
广州 30000 2012-06-22
北京 60000 2012-06-22
上海 50000 2012-06-22
(
城市 varchar(6),
金额 int,
日期 varchar(10)
)
insert into ab
select '广州', '20000', '2012-06-20' union all
select '北京', '30000', '2012-06-20' union all
select '上海', '30000', '2012-06-20' union all
select '广州', '20000', '2012-06-22' union all
select '北京', '30000', '2012-06-22' union all
select '上海', '30000', '2012-06-22' union all
select '广州', '20000', '2012-06-23' union all
select '北京', '30000', '2012-06-23' union all
select '上海', '30000', '2012-06-23'declare @begindate datetime
set @begindate='2012-6-18'
declare @enddate datetime
set @enddate='2012-6-30'create table #datetb
(
DT datetime
)while @begindate<=@enddate
begin
insert into #datetb
select @begindate
set @begindate=@begindate+1
end--查询
select b.城市,isnull(b.金额,0),a.DT 日期
from #datetb as a left join cb as b on a.DT=b.日期运行上面SQL后,得出的结果变成这样了:从结果看出,出现null的行,表示当天所有城市都没有数据的。例如:21号全天所有城市没有交易数据。
现在希望就是把 显示出来的数据也可以显示21号当天三个城市数据为0,而不希望出现null的城市名(实际数据中城市有几十个)。就是说一条null的数据,应该变成n条有城市名称的数据。请大家指教,十分感谢!!城市 金额 日期
广州 20000 2012-06-20
北京 30000 2012-06-20
上海 40000 2012-06-20
广州 0 2012-06-21
北京 0 2012-06-21
上海 0 2012-06-21
广州 30000 2012-06-22
北京 60000 2012-06-22
上海 50000 2012-06-22
order by a.DT
select a.城市,isnull(b.金额,0),a.DT 日期 from (select dt,城市 from #datetb as x cross join (select distinct 城市 from ab) as y )as a left join ab as b on a.DT=b.日期 and a.城市=b.城市
order by a.DT