Tsql 按天、月、年分组时sql缺少行
如果我按月、日、年从表组中选择,Tsql 按天、月、年分组时sql缺少行,tsql,date,grouping,Tsql,Date,Grouping,如果我按月、日、年从表组中选择, 它只返回有记录的行,而不返回没有任何记录的组合,这样一来,一眼就能看出每天或每月都有活动,您必须主动查看日期列以查找间隙。在T-SQL中,即使没有数据,如何获取每天/月/年的行?创建一个日历表,并在该表上使用外部联接。虽然它可能很粗糙,但它是我所用过的最好的方法,可以快速查询丢失的数据,或显示所有日期,或任何您想要检查某个范围内的值的内容,而不管是否使用该范围内的所有值。基于SqlNemage的说法,您可以使用交叉连接快速填充表或在内存中高效地创建表。 我收到了
它只返回有记录的行,而不返回没有任何记录的组合,这样一来,一眼就能看出每天或每月都有活动,您必须主动查看日期列以查找间隙。在T-SQL中,即使没有数据,如何获取每天/月/年的行?创建一个日历表,并在该表上使用外部联接。虽然它可能很粗糙,但它是我所用过的最好的方法,可以快速查询丢失的数据,或显示所有日期,或任何您想要检查某个范围内的值的内容,而不管是否使用该范围内的所有值。基于SqlNemage的说法,您可以使用交叉连接快速填充表或在内存中高效地创建表。 我收到了这段代码,下划线被转换成了破折号,因为StackOverflow正在损坏下划线-不需要数字表。我们的示例由于连接到另一个表而变得有点复杂,但也许有一天代码示例会帮助某些人
declare @career-fair-id int
select @career-fair-id = 125
create table #data ([date] datetime null, [cumulative] int null)
declare @event-date datetime, @current-process-date datetime, @day-count int
select @event-date = (select careerfairdate from tbl-career-fair where careerfairid = @career-fair-id)
select @current-process-date = dateadd(day, -90, @event-date)
while @event-date <> @current-process-date
begin
select @current-process-date = dateadd(day, 1, @current-process-date)
select @day-count = (select count(*) from tbl-career-fair-junction where attendanceregister <= @current-process-date and careerfairid = @career-fair-id)
if @current-process-date <= getdate()
insert into #data ([date], [cumulative]) values(@current-process-date, @day-count)
end
select * from #data
drop table #data
该任务要求将一组完整的日期保留在数据中,例如 声明@StartInt int 声明@Increment int 声明@Iterations int 设置为@StartInt=0 设置@Increment=1 设置@Iterations=365 选择 t完成的数据集。[日期] ,AggregatedMeasure=SUMISNULLt.Data,0 从…起 选择 [Date]=dateadddd,GeneratedInt,@StartDate 从…起 [dbo].[tvfUtilGenerateIntegerList] @StartInt, ,@增量, ,@Iterations t完成集 左连接tblData t 在t.[Date]=t完成日期集。[日期] 分组 t完成的数据集。[日期] 其中,表值函数tvfUtilGenerateIntegerList定义为 -示例输入 -声明@StartInt int -声明@Increment int -声明@Iterations int -设置为@StartInt=56200 -设置@Increment=1 -设置@Iterations=400 -声明@tblResults表 - -迭代ID int-identity1,1, -生成整数 - - ============================================= -作者:6eorge Jetson -创建日期:3333年11月22日 -描述:生成并返回所需的整数列表作为表 - ============================================= 创建函数[dbo]。[tvfUtilGenerateIntegerList] @StartInt int, @增量int, @迭代整数 返回 @tblResults表 迭代ID int-identity1,1, 生成整数 像 开始 声明@counter int 设置@counter=0 而@counter<@迭代 开始 插入@tblResultsGeneratedIntVALUES@StartInt+@计数器*@增量 设置@counter=@counter+1 终止 回来 终止 -调试 -从@tblResults中选择*