内部联接以查找同一修订号中的项目数

时间:2016-03-28 16:43:15

标签: sql ms-access ms-access-2007

我有以下表格

tblMainequipment
asset_id   rev    equipment_name
123        0      box
123        1      box 
124        0      box 
125        0      bottle  

tblmainswablocation
asset_id   rev   swab_location
123        0     cover
123        0     base
123        1     cover
123        1     base
123        1     lock
124        0     cover
124        0     base
125        0     tube
125        0     cover

我确实希望获得特定asset_id的最大转速的swablocations总数。例如,asset_id 123 rev 0的拖把位置总数是2,但是对于rev 1,它是3.我一直试图找出过去几个小时,但似乎无法找到解决方案。加入时我很糟糕。以下显示了我想要的内容,

query
asset_id   maxrev    #swablocation  equipment_name
123        1         3              box
124        0         2              cover
125        0         2              bottle

我使用以下sql

SELECT MEQ.*
FROM tblMainEquipment AS MEQ 
INNER JOIN (Select asset_id, max(rev) as maxrev     
            From tblmainequipment  GROUP By asset_id)  AS groupmeq ON 
            (MEQ.asset_id = groupmeq.asset_id) AND (MEQ.rev = groupmeq.maxrev)

我不确定如何将#swablocation添加到我的查询中。

2 个答案:

答案 0 :(得分:1)

你需要一个计数和一个小组

SELECT MEQ.asset_id maxrev, MEQ.maxrev, 
    count(blmainswablocations.swab_location), MEQ.equipment_name
FROM tblMainEquipment AS MEQ 
INNER JOIN (Select asset_id, max(rev) as maxrev     
        From tblmainequipment  GROUP By asset_id)  AS groupmeq ON 
        (MEQ.asset_id = groupmeq.asset_id) AND (MEQ.rev = groupmeq.maxrev)
Inner join blmainswablocations on MEQ.asset_id =  blmainswablocations.asset_id
Group by MEQ.asset_id maxrev

答案 1 :(得分:1)

以下是使用相关子查询的方法:

select me.*,
       (select count(*)
        from tblmainswablocation as sl
        where sl.asset_id = me.asset_id
       ) as numSwabs
from tblMainEquipment as me
where me.rev = (select max(me2.rev) from tblMainEquipment as me2 where me2.asset_id = me.asset_id);

优点是外部查询不需要聚合。