我有以下字段的单个表格。
id name startdate enddate
1 u1 2013-01-15 00:00:00.000 2013-01-17 00:00:00.000
2 u2 2013-01-22 00:00:00.000 2013-01-23 00:00:00.000
3 u3 2013-01-23 00:00:00.000 2013-01-23 00:00:00.000
现在,我希望多行取决于开始和结束日期。所以按照上面的行..它返回第一个记录的三行..日期15到17,返回3行(3天)。
我对查询感到有点困惑。有没有更好的方法或任何样本来实现?
感谢。
答案 0 :(得分:2)
您可以使用CTE来解决这个问题:
DECLARE @Id int
SELECT @Id = 1
;
WITH Multiple AS
(
SELECT 1 Sequence, Id, Name, StartDate, EndDate
FROM ( VALUES
(1, 'u1', '2013-01-15', '2013-01-17'),
(2, 'u2', '2013-01-22', '2013-01-23'),
(3, 'u3', '2013-01-23', '2013-01-23')
) AS Sample(Id, Name, StartDate, EndDate)
WHERE Id = @Id
UNION ALL
SELECT Sequence + 1, Id, Name, StartDate, EndDate
FROM Multiple
WHERE Id = @Id AND DATEADD(d, Sequence, StartDate) <= EndDate
)
SELECT *
FROM Multiple
答案 1 :(得分:0)
如果您的“日期”表格中有“日期”列,请将您的表格加入“Dates.Date BETWEEN startdate AND enddate”上的“日期”。
答案 2 :(得分:0)
我不太确定,但下面是我试过的......
SELECT c1.*
FROM master..spt_values p
INNER JOIN tempQuery c1
ON RIGHT(CAST(c1.stdate AS DATE),2) <= (CASE WHEN p.number = 0 THEN 1 ELSE p.number END)
WHERE TYPE='p'
AND p.number BETWEEN RIGHT(CAST(c1.stdate AS DATE),2) AND RIGHT(CAST(c1.endate AS DATE),2)