按DAY,MONTH,YEAR分组时sql缺少行
如果我按月,日,年从表组中选择,
它仅返回带有记录的行,而忽略不包含任何记录的组合,从而使我们似乎每天或者每个月都有活动,因此我们必须主动查看日期列以查找差距。在T-SQL中,即使没有数据,我如何每天/每月/每年都获得一行?
解决方案
回答
创建日历表并在该表上进行外部联接
回答
查看使用数字表。尽管这可能有点骇人听闻,但它是我快速查询丢失的数据,显示所有日期或者要检查范围内值的任何方法的最佳方法,无论是否使用了该范围内的所有值。
回答
在SQLMenace所说的基础上,我们可以使用CROSS JOIN快速填充表或者在内存中有效地创建表。
http://www.sitepoint.com/forums/showthread.php?t=562806
回答
我的开发人员使用此代码返回我,下划线转换为破折号,因为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 SET @StartInt = 0 SET @增量= 1 SET @迭代次数= 365 选择 tCompleteDateSet。[日期] ,AggregatedMeasure = SUM(ISNULL(t.Data,0)) 从 ( 选择 [日期] = dateadd(dd,GeneratedInt,@StartDate) 从 [dbo]。[tvfUtilGenerateIntegerList]( @StartInt, ,@增量, ,@迭代 ) )tCompleteDateSet 左联接tblData t 开启(t。[Date] = tCompleteDateSet。[Date]) 通过...分组 tCompleteDateSet。[日期]
表值函数tvfUtilGenerateIntegerList定义为
`
-示例输入
-DECLARE @StartInt int
-DECLARE @增量Int
-DECLARE @Iterations整数
-SET @StartInt = 56200
-SET @增量= 1
-SET @迭代次数= 400
-DECLARE @tblResults表
-(
-IterationId int identity(1,1),
-GeneratedInt int
-)
-============================================
-作者:6eorge Jetson
-创建日期:11/22/3333
-说明:生成并返回所需的整数列表作为表格
-===========================================
创建功能[dbo]。[tvfUtilGenerateIntegerList]
(
@StartInt int,
@Increment int,
@Iterations int
)
退货
@tblResults表
(
IterationId int identity(1,1),
GeneratedInt int
)
作为
开始
宣告@counter int
SET @计数器= 0
WHILE(@counter <@Iterations)
开始
插入@tblResults(GeneratedInt)值(@StartInt + @ counter * @ Increment)
SET @计数器= @计数器+ 1
结尾
返回
结尾
-调试
--SELECT *来自@tblResults
`