房屋
id OwnerId street
-----------------------
1 owner1 street1
2 owner2 street1
3 owner3 street2
4 owner4 street2
5 owner5 street3
正如您所看到的,在同一条街上可以有更多的所有者
我有另一张桌子,我希望从Houses
表中插入所有者,但每条街只有一个
查询结果:
表StreetRepresentant
ownerId street
------------------
owner1 street1
owner3 street2
owner5 street3
(ownerId
是表格的PK,如果重要的话。OwnerId
在表Houses
中是唯一的}
查询应该是:
INSERT INTO StreetRepresentant (ownerId , street )
SELECT ownerId , street
FROM Houses
--what should be here to get only 1 owner for each street? ...
答案 0 :(得分:3)
您可以按街道分组,然后使用MIN()
功能返回每条街道的最低值(根据您的示例)ownerId。
SELECT MIN(ownerId) , street
FROM Houses
GROUP BY street
答案 1 :(得分:0)
INSERT INTO StreetRepresentant (ownerId , street )
SELECT ownerId , street
FROM Houses h
GROUP BY h.street, h.ownerId
答案 2 :(得分:0)
看看像
这样的东西SELECT Street,
MIN(ID) FirstAvailableID
FROM Houses
GROUP BY Street
答案 3 :(得分:0)
在选择行时使用Distinct关键字,希望它能够正常工作。