通过sql在g​​roup上公开更多字段

时间:2014-07-08 14:22:48

标签: sql sql-server

我知道,在Group By中你不能Select一个不在聚合函数或GROUP BY子句中的字段。 < / p>

但是,必须有使用连接或其他方法的解决方法。

我有两个表BMP_VISITS_SITES和BMP_VISITS_COMMENTS,它们以一对多的关系由StationID连接。一个站点可以有很多评论。

我尝试编写一个返回所有网站和最新(仅1条)评论的查询。我有一个&#34;工作&#34;查询,但它只返回两个列,它们在聚合函数或组中。

这是我的工作&#34;查询:

select          a.StationID, 
                MAX(b.[dateobserved]) as LastDateObserved,
                a.Status
from            BMP_VISITS_SITES a
left outer join BMP_VISITS_COMMENTS as b 
on a.[StationID] = b.[StationID]
group by a.StationID;

但是如何访问两个表中的所有列?

我尝试了成功的内线联盟。当我将BMP_VISITS_SITES加入上述查询时,我得到了表的所有字段(t1)。很好,但是一旦我尝试加入BMP_VISITS_COMMENTS(t3),我得到的结果就会超出我的预期。

select          t1.*, t2.*
                --,t3.* 
                from BMP_VISITS_SITES t1
inner join (
        select a.StationID, MAX(b.[dateobserved]) as LastDateObserved from BMP_VISITS_SITES a
        left outer join BMP_VISITS_COMMENTS as b 
        on a.[StationID] = b.[StationID]
        group by a.StationID
) t2 on t2.StationID = t1.StationID
--inner join sde.BMP_VISITS_COMMENTS t3 on t3.StationID = t2.StationID;

2 个答案:

答案 0 :(得分:2)

SELECT a.*, b.* FROM
BMP_VISITS_SITES a
OUTER APPLY
(
    SELECT TOP 1 *
    FROM BMP_VISITS_COMMENTS b
    WHERE b.StationID = a.StationID
    ORDER BY LastDateObserved DESC
) b

您可以使用apply获取最后一条评论记录,并返回查询两侧的所有字段。

答案 1 :(得分:0)

使用row_number()

select * 
from 
(
    select          a.StationID, 
                    a.Status,
                    b.*,
                    row_number() over (partition by a.stationid, a.status order by b.[dateobserved] desc) as rn
    from            BMP_VISITS_SITES a
    left outer join BMP_VISITS_COMMENTS as b 
    on a.[StationID] = b.[StationID]
) v
where rn = 1