SELECT temp.hhid, temp.country, temp.max_prod, temp.max_area, gen.price_seed, gen.qty_seed, gen.price
FROM (SELECT hhid, country, MAX(area) AS max_area, max(total_prod) AS max_prod FROM gen GROUP BY hhid, country) AS temp, gen
WHERE (((temp.hhid)=gen.hhid) And ((temp.country)=gen.country) And ((temp.max_prod)=gen.total_prod) And ((temp.max_area)=gen.area))
ORDER BY temp.hhid;
为什么有些结果没有出现?
我至少有100个hhid,每个有3个区域,3个产品,种子数量,价格等... 所有hhid都显示在输出查询中,除了1 hhid,
可能出现什么问题?
答案 0 :(得分:0)
问题是prod
的最大值和area
的最大值很少在同一行。
您还应学习使用显式join
语法。一个简单的规则:永远不要在from
子句中使用逗号。
这可能是你想要的:
SELECT temp.hhid, temp.country, temp.max_prod, temp.max_area, gen.price_seed,
gen.qty_seed, gen.price
FROM gen INNER JOIN
(SELECT hhid, country, MAX(area) AS max_area, max(total_prod) AS max_prod
FROM gen
GROUP BY hhid, country
) AS temp
ON temp.hhid = gen.hhid AND temp.country = gen.country
WHERE (temp.max_prod = gen.total_prod or temp.max_area = gen.area)
ORDER BY temp.hhid;
我留下了WHERE
子句,因为MS Access对连接有奇怪的限制。从逻辑上讲,它应该放在ON
子句中,但我并不是100%确定Access是否接受该语法。