【发布时间】:2010-09-07 14:45:33
【问题描述】:
如果我按月、日、年从表组中选择, 它只返回有记录的行,而忽略没有任何记录的组合,让人一眼就看出每天或每月都有活动,您必须积极查看日期列是否有差距。如何在 T-SQL 中获取每天/每月/每年的一行,即使没有数据存在?
【问题讨论】:
如果我按月、日、年从表组中选择, 它只返回有记录的行,而忽略没有任何记录的组合,让人一眼就看出每天或每月都有活动,您必须积极查看日期列是否有差距。如何在 T-SQL 中获取每天/每月/每年的一行,即使没有数据存在?
【问题讨论】:
创建一个日历表并在该表上进行外部联接
【讨论】:
考虑使用numbers table。虽然它可能有点骇人听闻,但这是我用来快速查询缺失数据或显示所有日期或任何您想要检查某个范围内的值的最佳方法,无论是否使用了该范围内的所有值。
【讨论】:
基于 SQLMenace 所说,您可以使用 CROSS JOIN 快速填充表或在内存中高效地创建它。
http://www.sitepoint.com/forums/showthread.php?t=562806
【讨论】:
My developer 用这段代码回复了我,下划线转换为破折号,因为 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
【讨论】:
该任务要求将一组完整的日期左连接到您的数据中,例如
DECLARE @StartInt int
DECLARE @Increment int
DECLARE @Iterations int
SET @StartInt = 0
SET @Increment = 1
SET @Iterations = 365
SELECT
tCompleteDateSet.[Date]
,AggregatedMeasure = SUM(ISNULL(t.Data, 0))
FROM
(
SELECT
[Date] = dateadd(dd,GeneratedInt, @StartDate)
FROM
[dbo].[tvfUtilGenerateIntegerList] (
@StartInt,
,@Increment,
,@Iterations
)
) tCompleteDateSet
LEFT JOIN tblData t
ON (t.[Date] = tCompleteDateSet.[Date])
GROUP BY
tCompleteDateSet.[Date]
其中表值函数 tvfUtilGenerateIntegerList 定义为
-- Example Inputs
-- DECLARE @StartInt int
-- DECLARE @Increment int
-- DECLARE @Iterations int
-- SET @StartInt = 56200
-- SET @Increment = 1
-- SET @Iterations = 400
-- DECLARE @tblResults TABLE
-- (
-- IterationId int identity(1,1),
-- GeneratedInt int
-- )
-- =============================================
-- Author: 6eorge Jetson
-- Create date: 11/22/3333
-- Description: Generates and returns the desired list of integers as a table
-- =============================================
CREATE FUNCTION [dbo].[tvfUtilGenerateIntegerList]
(
@StartInt int,
@Increment int,
@Iterations int
)
RETURNS
@tblResults TABLE
(
IterationId int identity(1,1),
GeneratedInt int
)
AS
BEGIN
DECLARE @counter int
SET @counter= 0
WHILE (@counter < @Iterations)
BEGIN
INSERT @tblResults(GeneratedInt) VALUES(@StartInt + @counter*@Increment)
SET @counter = @counter + 1
END
RETURN
END
--Debug
--SELECT * FROM @tblResults
【讨论】: