首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Server中使用递归CTE获取所有ids的数据

问在Server中使用递归CTE获取所有ids的数据
EN

Stack Overflow用户
提问于 2020-01-14 14:46:52
回答 1查看 312关注 0票数 0

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

我的逻辑是

代码语言:javascript
复制
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

我试过这样做

代码语言:javascript
复制
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

我得到了

在递归公共表表达式“cte_org”的递归部分不允许将SQL 467分组为、拥有或聚合函数。

有什么帮助吗?

编辑

预期结果

代码语言:javascript
复制
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

代码语言:javascript
复制
id   time          color
1    14/1/2020     pink
2    14/1/2020     black
3    14/1/2020     orange
EN

回答 1

Stack Overflow用户

发布于 2020-01-14 15:18:18

代码语言:javascript
复制
    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

或

代码语言:javascript
复制
    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

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59736128

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档