SQL select 每个 parent/child 项系列的日期范围

SQL select a date range for each parent/child family of items

我为所有具有范围键的 parent/child 类型项目构建了一个层次结构 (temp table)。我有一个 table (LastOrdr),其中包含所有商品的最后订购日期(无论 parent/child)。然后我有了包含所有项目的主项目 table。

我有一个查询 select 所有非 parent/child 项目满足特定的最后订单日期条件。这是一个简单的查询,它将主项目 table 与 LastOrdr table 连接起来,以从提供的用户参数中获取 max(lastorderdate)。

我的挑战是对 parent/child 产品做同样的事情。对于 parent/child 个项目(一个 parent 并且最多可以有 8 个 child,但在大多数情况下是 2/3)。 selection 是,对于一个家庭,max(lastorderdate) 必须应用于整个家庭。我的意思是,如果我有一个 parent 的 3 child,我需要找到这个系列中所有 4 个(1 个 parent 和 3 个 child)项目的最大值来自 LastOrdr.lastorderdate,然后将其与用户提供的参数进行比较。如果它符合家庭标准,我想select那个家庭,否则,放弃它。

将不胜感激一些实现此目的的指导。

谢谢。

表 1(主条目):

itemID    ParentID    Descrip    ......
21         2           .....
22         2           .....
23         2           .....
24         2           .....
27         3           .....
29         3           .....
33         3           .....
41         3           .....
......................

表 2 (LastOrdr):

ItemID    lastorderdate
2          2014-01-01
21         2014-07-21
21         2015-01-12
22         2013-01-01
23         2014-04-01
27         2013-01-23
...........................

你没有 post 任何 table 结构,所以我只给出我的一般方法。 首先,我将通过创建一个附加列来标识分组来对 parents 和 children 进行分组。我会 UNION parents 和 children,以及附加列 parentId

itemId | parentId
1      | 1
2      | 1
7      | 1
9      | 1
3      | 3
6      | 3

从这里,您可以GROUP BY parentId获得MAX(lastorderdate)。如果你 post table 结构,我可以更详细。

试试下面的查询:

SELECT *
FROM (
    SELECT a.ParentID, MAX(orderdate) AS 'LatestOrder'
    FROM table1 a
    JOIN Table2 b ON b.ItemID = a.ItemID
    GROUP BY ParentID
) c
JOIN table2 d ON d.OrderDate = c.LatestOrder
JOIN table1 e ON e.ItemId = d.ItemId AND e.ParentId = c.ParentID 

下面查询returns你想要什么。

declare @master table (itemID int, ParentID int)
insert @master values
(21         ,2 ),
( 22         ,2), 
( 23         ,2 ),
( 24         ,2 ),
( 27         ,3 ),
( 29         ,3 ),
( 33         ,3 ),
( 41         ,3),
(2, 2), --I added this data
(3, 2)  --
--,(44,21) --if you wish grandchild

declare @LastOrdr table(ItemID int, lastorderdate date)
insert @LastOrdr values
(2          ,'2014-01-01'),
(21         ,'2014-07-21'),
(21         ,'2015-01-12'),
(22         ,'2013-01-01'),
(23         ,'2014-04-01'),
(27         ,'2013-01-23')
--,(44, '2015-04-15') --grandchild's order

;with master as (--create recursive (hierarchical) CTE
--anchor query: items w/out parents
select itemid, itemid ParentID --fix value
from @master where ParentID = itemId --parent to itsellf
union all
--recursive query down the tree
select m.itemid, m1.ParentID
from @master m
inner join master m1 on m.ParentID=m1.itemID
)--end CTE
select m.ParentID, max( lo.lastorderdate) lastorderdate
from master m
inner join @LastOrdr lo on m.itemID=lo.ItemID --join by childId
where lo.lastorderdate< '2015-05-29' -- use ISO date
group by m.ParentID --group by parent