SQL创建具有层次结构的表

时间:2018-04-09 20:11:13

标签: sql sql-server

有人会帮忙构建表并查询吗?谢谢你的时间!

假设以下是我拥有的手机的记录:

ID    | Object            | Start Month | End Month 
1     | Phone 1           |     1       |   3      
2     | Phone 1 OS Update |     2       |   3      
3     | Phone 2           |     4       |   5
4     | Phone 3           |     6       |   7

Desired result
Query: Month = 2; Return ID = 1,2 (Logic: Phone 1 with its OS update)
Query: Month = 4; Return ID = 3 (Logic: Phone 2 replaces Phone 1 and update)
Query: Month = 6; Return ID = 4 (Logic: Phone 3 replaces Phone 2)

现在,我正在制作一个单独的表格,其打印时间如下。

ID       | Object            | Month    
1        | Phone 1           |     1           
1        | Phone 1           |     2        
2        | Phone 1 OS Update |     2          
1        | Phone 1           |     3 
2        | Phone 1 OS Update |     3       
3        | Phone 2           |     4      
3        | Phone 2           |     5   
4        | Phone 3           |     6 
4        | Phone 3           |     7   

SELECT [ID]
FROM Table
WHERE MONTH = 2

我还添加了一个额外的列,其id为下一个" superior"电话。是否可以自动生成此表而无需每月手动插入每一行?如果此表效率低下,我该如何构造表然后进行查询?

ID       | Object            | Month | Superior Object ID     
1        | Phone 1           |     1 |   3            
1        | Phone 1           |     2 |   3         
2        | Phone 1 OS Update |     2 |   1          
1        | Phone 1           |     3 |   3  
2        | Phone 1 OS Update |     3 |   1       
3        | Phone 2           |     4 |   4       
3        | Phone 2           |     5 |   4   
4        | Phone 3           |     6 |   NULL   
4        | Phone 3           |     7 |   NULL     

0 个答案:

没有答案