我正在尝试获取我的数据库中存在的一系列日期和相应的值(如果有的话)。
我有两个参数 - 今天(使用getDate()的日期) - 以及天数(整数)。对于这个例子,我使用的值为10天。
获取今天之后10天的连续日期的代码:
SELECT top 10 DATEADD(DAY, ROW_NUMBER()
OVER (ORDER BY object_id), REPLACE(getDate(),'-','')) as Alldays
FROM sys.all_objects
我现在需要在连续日期代码中查找每天的几个值,这些值可能存在于时间表中,也可能不存在(我们假设所有日期都是8小时,除非另有说明)。查找将在字段recordDateTime上。如果该日期的表cap_time中不存在“小时”值,则需要返回默认值8作为小时数。这是基本查询:
SELECT u.FullName as UserName, d2.department,
recordDateTime, ISNULL(hours,8) as hours
FROM cap_time c
left join user u on c.userID = u.userid
left join dept d2 on u.deptID = d2.DeptID
WHERE c.userid = 38 AND u.deptID = 1
我接下来10天的最终结果应该是这样的: 日期(顺序),部门,用户名,小时数
我可以使用TSQL和临时表完成此操作,但我想看看是否可以在单个语句中完成此操作。任何帮助表示赞赏。
答案 0 :(得分:0)
没有任何DDL或样本数据,很难确切地确定您需要什么。
我认为这会让你非常接近(请注意我的评论):
-- sample data
------------------------------------------------------------------------------------------
DECLARE @table TABLE
(
fullName varchar(10),
department varchar(10),
[hours] tinyint,
somedate date
);
INSERT @table VALUES
('bob', 'sales', 5, getdate()+1),
('Sue', 'marketing', 3, getdate()+2),
('Sue', 'sales', 12, getdate()+4),
('Craig', 'sales', 4, getdate()+8),
('Joe', 'sales', 18, getdate()+9),
('Fred', 'sales', 10, getdate()+10);
--SELECT * FROM @table
;
-- solution
------------------------------------------------------------------------------------------
WITH alldays([day]) AS -- logic to get your dates for a LEFT date table
(
SELECT TOP (10)
CAST(DATEADD
(
DAY,
ROW_NUMBER() OVER (ORDER BY object_id),
getdate()
) AS date)
FROM sys.all_objects
)
SELECT d.[day], t.fullName, department, [hours] = ISNULL([hours], 8)
FROM alldays d
LEFT JOIN @table t ON d.[day] = t.somedate;
结果:
day fullName department hours
---------- ---------- ---------- -----
2017-04-12 bob sales 5
2017-04-13 Sue marketing 3
2017-04-14 NULL NULL 8
2017-04-15 Sue sales 12
2017-04-16 NULL NULL 8
2017-04-17 NULL NULL 8
2017-04-18 NULL NULL 8
2017-04-19 Craig sales 4
2017-04-20 Joe sales 18
2017-04-21 Fred sales 10
答案 1 :(得分:0)
可能是子查询和in语句,如:
SELECT u.FullName as UserName, d2.department,
recordDateTime, ISNULL(hours,8) as hours
FROM cap_time c
left join user u on c.userID = u.userid
left join dept d2 on u.deptID = d2.DeptID
WHERE c.userid = 38 AND u.deptID = 1 and recordDateTime in
(SELECT top 10 DATEADD(DAY, ROW_NUMBER()
OVER (ORDER BY object_id), REPLACE(getDate(),'-','')) as Alldays
FROM sys.all_objects)