我不确定如何在SQL中表达这一点,如果它甚至可能,或者甚至可以调用它。
对于表A中的每条记录,我希望表B中的第一个最佳匹配记录尚未被选为最佳匹配。例如,假设我有一个通用购物清单和食物菜单:
Table A Table B
Generic Shopping List Food Menu
--------------------- ----------------------
Food Type Food Food Type
--------------------- ----------------------
Meat Tomatoes Vegetable
Meat Lettuce Vegetable
Vegetable Bacon Vegetable
Vegetable Bacon Meat
Vegetable Beef Meat
Vegetable Apple Fruit
Fruit Orange Fruit
Fruit Bacon Fruit
Dairy Milk Dairy
Cheese Dairy
Yogurt Dairy
通过查询或加入,您很容易获得前1名匹配:
Table/Query C
Automagic Shopping
------------------
Food
------------------
Bacon
Bacon
Tomatoes
Tomatoes
Tomatoes
Tomatoes
Apple
Apple
Milk
我知道怎么做,因为我喜欢培根,我可以忍受这个。不幸的是,我真的需要全方位的食物选择,以便我有可用的插槽。
Table/Query C
Better Magic Shopping
---------------------
Food
---------------------
Bacon
Beef
Tomatoes
Lettuce
Bacon
<NULL - No More Available Matches - Don't Care>
Apple
Orange
Milk
如果可以在Access中完成,那很好。如果它不能在Access中完成,但可以在其他产品中完成,那么它不是理想的,但它是可行的。
感谢。
答案 0 :(得分:3)
这是在SQL Server中执行此操作的方法:
SELECT t1.FoodType, t2.Food
FROM (
SELECT *, ROW_NUMBER() OVER (PARTITION BY FoodType ORDER BY FoodType) AS rn
FROM #tableA ) AS t1
LEFT JOIN (
SELECT *, ROW_NUMBER() OVER (PARTITION BY FoodType ORDER BY FoodType) AS rn
FROM #tableB) AS t2 ON t1.FoodType = t2.FoodType AND t1.rn = t2.rn
下面是两个子查询t1
,t2
计算的表表达式:
Results for t1: Results for t2:
FoodType rn Food FoodType rn
--------------- --------------------------
Dairy 1 Milk Dairy 1
Fruit 1 Cheese Dairy 2
Fruit 2 Yogurt Dairy 3
Meat 1 Apple Fruit 1
Meat 2 Orange Fruit 2
Vegetable 1 Bacon Fruit 3
Vegetable 2 Bacon Meat 1
Vegetable 3 Beef Meat 2
Vegetable 4 Tomatoes Vegetable 1
Lettuce Vegetable 2
Bacon Vegetable 3
在LEFT JOIN
和FoodType
上执行rn
可以获得您想要的效果。
答案 1 :(得分:0)
Access允许使用NOT IN子句。只需编写查询即可获得TOP 1匹配。然后将此查询作为NOT IN子句中的子查询包含在内。
Select * From Table_A A, Table_B B Where A.Food_Type = B.Food_Type And B.Food Not In (Select Top 1 D.Food From Table_A D, Table_B C Where D.Food_Type = D.Food_Type And C.Food_Type = 'give your criterion value here')
请注意,您可能希望使用合适的Order By子句来描述如何确定什么是最佳匹配以及什么是不匹配。