0

我有一个包含三列的 sql 表

id, balance, datetime 我想通过给出持续时间从表中获取数据。假设我想获取 2013 年 1 月 1 日到 2013 年 1 月 15 日之间的数据。给出的数据表如下:

#id   Datetime  Balance #
1     1/1/2013   1500
2     1/2/2013   2000
3     1/4/2013   1500
4     1/5/2013   2500

现在我想要输出为

#id  Datetime  Balance #
1    1/1/2013   1500
2    1/2/2013   2000
3    1/3/2013    0
4    1/4/2013   1500
5    1/5/2013   2500

我想显示所有日期以及日期是否没有余额。它显示 O 或 null 值

4

3 回答 3

1

我会删除 ID 列,因为当您添加其他行并执行以下操作时它是无用的:

set dateformat mdy 

declare @tmpTable table (dates date)

declare @startDate date = '1/1/2013'
declare @endDate date = '1/15/2013'

while @startDate <= @endDate
begin
    insert into @tmpTable (dates) values (@startDate)
    set @startDate = DATEADD(DAY, 1, @startDate)
end

select tmp.dates, yourtable.balance 
from @tmpTable as tmp
left outer join yourTable on yourTable.[Datetime] = tmp.dates
where yourtable.[Datetime] between @startDate and @endDate
于 2013-09-18T11:29:18.473 回答
0

您可以通过创建一个 cte 来做到这一点,其中包含您的日期范围和外部将它与您的表连接起来的日期。

with cte as
 (
 select start_date dt
 union all
 select dateadd(dd,1,dt) from cte where dt < end_date
)
select id, cte.dt, balance from cte left outer join yourtable b on cte.dt = b.date;
于 2013-09-18T11:37:41.327 回答
0

我不确定您使用的是哪种 SQL,但您可以创建一个包含所有日期的表并对其进行外部连接。例如,如果您有一个名为“日期”的所有日期表,那么您可以这样做:

从表 1 中选择 id、dateTime、余额

于 2013-09-18T11:16:02.303 回答