0

我有 2 个表,表 2 包含许多商店地址。表 2 按 Shop_ID 引用表 1 我想像那样选择 [见图] 请帮帮我!

在此处输入图像描述

4

1 回答 1

0

你可以使用row_number()

select shop_id, 
  shop_name,
  shop_address
from
(
  select t1.shop_id,
    t1.shop_name,
    t2.shop_address,
    row_number() over(partition by t1.shop_id
                      order by t1.shop_name, t2.shop_address) rn
  from table_1 t1
  inner join table_2 t2
    on t1.shop_id = t2.shop_id
) src
where rn = 1

查看关于 SQL Fiddle 的演示

您还可以使用聚合函数:

select t1.shop_id, 
  t1.shop_name,
  max(t2.shop_address) shop_address
from Table1 t1
inner join table2 t2
  on t1.shop_id = t2.shop_id
group by t1.shop_id, t1.shop_name

请参阅带有演示的 SQL Fiddle

于 2013-01-15T18:40:12.903 回答