关于count中的记录为0的问题

sxzkf 2009-06-28 06:12:37
试图用sql中的count查询数据库,但是不满足条件的记录总是不被显示,即满足条件的记录为0,这样的如何显示?

某时间段内,如2009年1月1日至3日,每一天符合条件的记录是多少?
输出:
2009年1月1日 20
2009年1月2日 10

但是2009年1月3日没有符合条件的记录,但并不输出任何结果。
我现在想把为0的记录也输出,请教大家。
PS:我用asp
...全文
213 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
ai_li7758521 2009-06-28
  • 打赏
  • 举报
回复
declare @Bdate smalldatetime,@Edate smalldatetime,@i int
select @Bdate='2009-01-01',@Edate='2009-01-03',@i=datediff(dd,@Bdate,@Edate)

declare @c table([date] smalldatetime,cnt int)
insert @c
select '2009-01-01',20 union all
select '2009-01-01',1 union all
select '2009-01-02',10


declare @date table(date smalldatetime)

while(@i>=0)
begin
insert @date
select dateadd(dd,0-@i,@Edate)
select @i=@i-1
end

select a.[date],cnt=sum(isnull(cnt,0))
from @date a left join @c b
on a.date=b.date
group by a.date

date cnt
----------------------- -----------
2009-01-01 00:00:00 21
2009-01-02 00:00:00 10
2009-01-03 00:00:00 0

(3 行受影响)
htl258_Tony 2009-06-28
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 sxzkf 的回复:]
引用 1 楼 htl258 的回复:
生成一日期列,再進行左連接。



有无例句?
[/Quote]
3樓寫出來了。
sxzkf 2009-06-28
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 htl258 的回复:]
生成一日期列,再進行左連接。
[/Quote]

有无例句?
sxzkf 2009-06-28
  • 打赏
  • 举报
回复
有无例句?谢谢!
playwarcraft 2009-06-28
  • 打赏
  • 举报
回复

declare @be datetime,@en datetime
set @be='2009-1-1'
set @en='2009-1-3'

select A.[date],sum(case when 某栏位 is null then 0 else 1 end) as [cnt]
from
(
select distinct dateadd(day,number,@be) as [date]
from master.dbo.spt_values
where number between 0 and datediff(day,@be,@en)
) A
left join 表名 B
on A.[date]=B.[date]
group by A.[date]
rucypli 2009-06-28
  • 打赏
  • 举报
回复
create table test ( a datetime)

declare @num int
set @num = 1
while @num < 1000
begin
insert into test values(convert(varchar(10),getdate()-@num,120)
set @num = @num - 1
end
htl258_Tony 2009-06-28
  • 打赏
  • 举报
回复
生成一日期列,再進行左連接。

22,209

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧