从另一个表中的每个ID的表中选择前1

时间:2011-02-22 01:15:39

标签: sql sql-server tsql

表结构是:

create table fruit (
  id int identity(1,1),
  name varchar(max)
)

create table fruit_allocation (
  id int identity(1,1),
  fruit_id int references fruit(id),
  customer_id int references store(id),
  amount float,
)

create table measurement (
  fruit_allocation_id int references fruit_allocation(id),
  measurement_date datetime,
  measurement float,
)

每个水果都可以分配给多个客户,创建一个fruit_allocation记录。每个fruit_allocation记录可以有多个度量值。

我想在给出水果ID

的情况下为每个fruit_allocation选择最新的测量值

到目前为止,我有以下内容:

select * 
  from measurement 
 where fruit_allocation_id in (select id 
                                 from fruit_allocation 
                                where fruit_id = 10)

这将返回该水果的所有测量值,我想在每个fruit_allocation返回1个测量值。

4 个答案:

答案 0 :(得分:9)

你可以CROSS APPLY

select a.*, m.*
from fruit_allocation a
cross apply (
    select top 1 *
    from measurement m
    where m.fruit_allocation_id = a.id
    order by m.measurement_date desc
) m
where a.fruit_id = 10

答案 1 :(得分:1)

假设您使用的是SQL Server 2005 +

With RankedMeasurements As
    (
    Select M.fruit_allocation_id
        , M.measurement_date
        , M.measurement
        , Row_Number() Over ( Partition By M.fruit_allocation_id 
                                Order By M.measurement_date Desc ) As Rnk
    From measurement As M
    Where Exists    (
                    Select 1
                    From fruit_allocation As FA1
                    Where FA1.id = M.fruit_allocation_id
                        And FA1.fruit_id = 10
                    )   
    )
Select RM.fruit_allocation_id
    , RM.measurement_date
    , RM.measurement
From RankedMeasurements As RM
Where Rnk = 1

答案 2 :(得分:0)

创建一个子查询以查找每个分配的最新度量,然后加入该子查询,就像它是一个真实的表一样。

select * from measurement meas
join
        (
        SELECT  fruit_allocation_id,
                MAX(measurement_date) as max_date
        FROM    measurement meas2
        JOIN    fruit_allocation alloc
        ON      alloc.id = meas2.fruit_allocation_id
        where fruit_id = 10
        ) max_meas
on      meas.fruit_allocation_id = max_mes.fruit_allocation_id
and     meas.measurement_date = max_meas.max_date

答案 3 :(得分:0)

选择*   从测量m  其中measurement_date =(从测量m1中选择前1个measurement_date                 其中m1.fruit_allocation_id = m.fruit_allocation_id                 按measure_date desc排序)  和  fruit_allocation_id in(选择id                                  来自fruit_allocation                                 其中fruit_id = 3)