SQL查询从两个表中选择具有最小值的不同行

时间:2015-12-25 08:38:44

标签: mysql sql-server

我想要一个sql查询来获取最少price的产品行,并获取两个表的所有其他字段。

考虑下表:

T1:                  T2:
id   Title           id pcount price t1_id(foreign key)
1    x               1  3      3000  2
2    y               2  8      2500  2
3    z               3  4      1200  1
                     4  6      1000  1
                     5  9      4000  3

如何选择price列中具有最小值的以下列,按Title分组并获取以下字段?像这样:

id   Title pcount  price t1_id   
1    y     8       2500  2
2    x     6       1000  1
3    z     9       4000  3 

4 个答案:

答案 0 :(得分:0)

对于Sql Server,您可以使用OUTER APPLY

select * from t1
outer apply(select top 1 * from t2 where t1_id = t1.id order by price) oa

答案 1 :(得分:0)

试试这个,

SELECT t1.*,
       t3.*
FROM   T1 t1
       CROSS apply (SELECT Min(price) AS price
                    FROM   T2
                    WHERE  t1_id = t1.tableid)t2
       LEFT OUTER JOIN t2 t3
                    ON t3.t1_id = t1.tableid
                   AND t3.price = t2.price

答案 2 :(得分:0)

select * 
    from t1 
      left join 
         (select pcount, price, t2.t1_id 
              from t2 
                 join 
                   (select t1_id, min(price) pmin 
                        from t2 
                      group by t1_id
                   ) tt 
            where t2.t1_id = tt.t1_id and price = pmin
          ) tt1 
     on t1.id = tt1.t1_id

结果

id  Title   pcount  price   t1_id
1   x       6       1000    1
2   y       8       2500    2
3   z       9       4000    3

答案 3 :(得分:0)

同时检查:

declare @t1 table(id int , title varchar(50))
declare @t2 table(id int , pcount int, price int, t1_id int)

insert into @t1 values (1, 'x' ), (2,'y'), (3,'z')

insert into @t2 values (1, 3, 3000, 2 ), (2, 8, 2500, 2 ),(3, 4, 1200, 1 ),(4, 6, 1000, 1),(5, 9, 4000, 3)

;with cte
as(
    select * from (select * , ROW_NUMBER() OVER (PARTITION BY t1_id ORDER BY t1_id asc, price asc ) AS sequence_id from @t2 ) a where sequence_id = 1
  ) 

  select t1.*, cte.pcount ,cte.price from @t1 t1 join cte on t1.id = cte.t1_id     

 --or understand more

;with cte as
(
select t1_id, min(price) price
from @t2 group by t1_id 
)
, cte1 as
(
select t1.*,t2.pcount, cte.* from @t1 t1 
left outer join @t2  t2 on t1.id = t2.t1_id 
left outer join cte  cte on t1.id = cte.t1_id and (t2.t1_id  =cte.t1_id and t2.price = cte.price)
)
select * from cte1 where t1_id is not null