基于另一个表的链接结果的where子句进行查询

问题描述 投票:0回答:1

我的数据库中有3个表。表A包含项目的主要ID和标题。表B是该项目的主要详细信息表,我们记录了对其进行的每次更新的新记录。表C用于可以添加到项目中的部门,每个记录可以有多个。

表A

TAID | Name
-------------
1   |  Test 1  
2   |  Test 2  
3   |  Test 3  

表B

TANo   |   TAID   |   Description   |  Completed
------------------------------------------------
1      |   1      |   Some text     |  True
2      |   1      |   More text     |  True
3      |   1      |   Extra text    |  False
4      |   2      |   Other text    |  True
5      |   2      |   Test text     |  True
6      |   3      |   Text          |  True

表C

DivID   |   TANo   |   TAID   |   DivisionID
------------------------------------------------
1      |   1      |    1      |   1
2      |   1      |    1      |   2
3      |   2      |    1      |   2
4      |   3      |    1      |   2
5      |   6      |    3      |   4

我想写一个查询,使我可以提取ID的最新记录,但按部门细分。我的查询只是获取表B到表A的最新行,但是我被困在如何查询我的结果的基础上,例如我想获得1分部的所有结果?还是多个部门?

 Select 
 ta.Name
,tb.TANo
,tb.TAID
,tb.Description
,tb.Completed
From
TableA ta

CROSS APPLY
(
    Select
    Top(1)
     b.TANo
    ,b.TAID
    ,b.Description
    ,b.Completed
    From
    TableB as b
    Where
    b.TAID = ta.TAID 
    Order by b.TANo desc
) as tb
sql sql-server tsql where-clause greatest-n-per-group
1个回答
0
投票

如果需要每个分区的tableb中的最新记录,可以加入并使用窗口函数进行过滤:

select *
from (
    select 
        c.divisionId, 
        b.description, 
        b.completed, 
        row_number() over(partition by c.divisionId order by tano desc) rn
    from tablec c
    inner join tableb b on b.tano = c.tano
) t
where rn = 1

当然您也可以引入tablea

select *
from (
    select 
        c.divisionId, 
        b.description, 
        b.completed, 
        a.name
        row_number() over(partition by c.divisionId order by tano desc) rn
    from tablec c
    inner join tableb b on b.tano = c.tano
    inner join tablea a on a.taid = b.taid
) t
where rn = 1

注意:目前尚不清楚为什么要同时在taidtableb中存储tablec;就tableb中的记录而言,它属于单个项目,因此显然不需要在tablec中存储冗余信息。

© www.soinside.com 2019 - 2024. All rights reserved.