SQL SELECT WHERE麻烦任何有用的想法

时间:2009-05-19 21:34:32

标签: sql sql-server sql-server-2005 join where

我有两个表父母和孩子(在PK / FK GUID上相关)

Child有一个时间戳(记录创建日期/时间)。

我想要做的只是获取最新的子记录和父记录,FOR EACH父记录。

SELECT 
    dbo_Parents.ParentName, 
    dbo_ChildEntry.CountPropertys, 
    dbo_ChildEntry.DateTimeStamp
FROM 
    dbo_Parents INNER JOIN dbo_ChildEntry 
ON
    dbo_Parents.ParentID = dbo_ChildEntry.ParentID
WHERE 
    ([WHAT SHOULD BE HERE?]))

5 个答案:

答案 0 :(得分:8)

假设您想要最近的条目,您必须使用TOP 1并按顺序排序。

SELECT TOP 1
dbo_Parents.ParentName, 
dbo_ChildEntry.CountPropertys, 
dbo_ChildEntry.DateTimeStamp 
FROM dbo_Parents 
INNER JOIN dbo_ChildEntry ON dbo_Parents.ParentID = dbo_ChildEntry.ParentID 
ORDER BY dbo_ChildEntry.DateTimeStamp desc

澄清后编辑:“最近的子记录和父记录,FOR EACH父记录”:

WHERE dbo_ChildEntry.DateTimeStamp = 
      ( Select Max( dbo_ChildEntry.DateTimeStamp )
               from dbo_ChildEntry 
               where dbo_Parents.ParentID = dbo_ChildEntry.ParentId )

答案 1 :(得分:3)

WHERE dbo.ChildEntry.DateTimeStamp = ( Select Max( c.DateTimeStamp )
                                         from dbo.ChildEntry c
                                        where dbo_Parents.ParentID = c.ParentId )

答案 2 :(得分:1)

select p.ParentName, 
    c.CountPropertys, 
    c.DateTimeStamp
from (
    select max(DateTimeStamp) as DateTimeStamp, ParentID
    from dbo_ChildEntry
    group by ParentID) cm
inner join dbo_ChildEntry c on cm.DateTimeStamp = c.DateTimeStamp and cm.ParentID = c.ParentID
inner join dbo_Parents p on c.ParentID = p.ParentID

答案 3 :(得分:0)

既然你澄清了你想要每个父母一行,试试这个。对于每一行,它搜索具有较晚时间戳的子行。在WHERE子句中,它过滤了没有“下一个”子节点的行。

SELECT 
    dbo_Parents.ParentName, 
    cur.CountPropertys, 
    cur.DateTimeStamp
FROM dbo_Parents 
INNER JOIN dbo_ChildEntry cur
    ON dbo_Parents.ParentID = cur.ParentID
LEFT JOIN dbo_ChildEntry next
    ON dbo_Parents.ParentID = next.ParentID
    AND next.DateTimeStamp > cur.DateTimeStamp
WHERE
    next.DateTimeStamp is null

答案 4 :(得分:-1)

尝试

SELECT     dbo_Parents.ParentName,     dbo_ChildEntry.CountPropertys,     
max(dbo_ChildEntry.DateTimeStamp)
FROM     dbo_Parents 
INNER JOIN dbo_ChildEntry ON    dbo_Parents.ParentID = dbo_ChildEntry.ParentID
group by dbo_Parents.ParentName,     dbo_ChildEntry.CountPropertys