在SQL Server中使用递归CTE获取所有ID的数据

在SQL Server中使用递归CTE获取所有ID的数据,sql,sql-server,common-table-expression,recursive-query,Sql,Sql Server,Common Table Expression,Recursive Query,我试图在sql中使用递归CTE来获取表中每个唯一id的数据。我正在阅读,但无法使代码正常工作 我的逻辑是 for each unique id in a table = currentId select * from table where date between max available date of that currentId and 5 days before that max available date of that currentId 我试着这么做 WITH cte_

我试图在sql中使用递归CTE来获取表中每个唯一id的数据。我正在阅读,但无法使代码正常工作

我的逻辑是

for each unique id in a table = currentId
select * from table
where 
date between
max available date of that currentId
and 
5 days before that max available date of that currentId
我试着这么做

WITH cte_org AS (
    SELECT * FROM shoes 
    UNION ALL
    SELECT * 
    FROM cte_org 
    WHERE  
    CAST(startTime AS date) 
    BETWEEN  DATEADD(DAY,-30, (select max(CAST(startTime as date)) from shoes where shoeId = cte_org.shoeId )  )
    AND (select max(CAST(startTime as date)) from shoes where shoeId = cte_org.shoeId )
)

 SELECT * FROM cte_org
我明白了

SQL错误467在递归公共表表达式“cte_org”的递归部分不允许使用GROUP BY、HAVING或AGGRATE函数

有什么帮助吗

编辑

预期结果

for shoe id 1
time 14/1/2020 - color black
time 13/1/2020 - color yellow
time 12/1/2020 - color pink
time 11/1/2020 - color orange
time 10/1/2020 - color green

for shoe id 2
time 14/1/2020 - color white
time 13/1/2020 - color green
time 12/1/2020 - color black
time 11/1/2020 - color blue
time 10/1/2020 - color brown

for shoe id 3....etc
编辑2

id   time          color
1    14/1/2020     pink
2    14/1/2020     black
3    14/1/2020     orange


请尝试上述查询,如果有语法错误,请尝试更正,但这是正确的逻辑。

为什么需要rCTE来获取每个ID的数据?当然,如果你不过滤,你会得到所有的ID。样本数据和预期结果很好地帮助了我们。@Larnu请检查编辑的问题,以查看预期结果的形式。谢谢现在需要样本数据。@Larnu我如何上传样本数据?从来没有像你那样做过,预期的结果是好的。如果你想做得更好,可以像DDL和DML那样做。原则上你是对的,想法不错。但在实践中,我仍然得到
SQL错误467在递归公共表表达式“cte_org”的递归部分不允许使用GROUP BY、HAVING或AGGRATE函数。我需要以某种方式摆脱介于
之间的
?这是一个聚合函数吗?谢谢\
    WITH cte_org AS (
        SELECT * FROM shoes 
        UNION ALL
        SELECT * 
        FROM cte_org 
        WHERE  
        CAST(startTime AS date) 
        BETWEEN  DATEADD(DAY,-30, (select max(CAST(startTime as date)) from shoes where shoeId = cte_org.shoeId )  )
        AND (Select top 1 CAST(startTime as date) 
 from shoes where shoeId = cte_org.shoeId 
Order by startTime desc)
    )

 SELECT * FROM cte_org
    WITH cte_org AS (
        SELECT * FROM shoes 
        UNION ALL
        SELECT * 
        FROM cte_org 
        WHERE  
        CAST(startTime AS date) 
        BETWEEN  DATEADD(DAY,-30, (select max(CAST(startTime as date)) from shoes where shoeId = cte_org.shoeId )  )
        AND (Select Max(CAST(startTime as date)) OVER ( Partition by shoeId) AS max_date
 from shoes where shoeId = cte_org.shoeId )
    )

 SELECT * FROM cte_org