我正在使用sql,有4个不同的列,分别是pname,Fname,Flastname和amount。它为pname和amount提供了正确的输出,但fname和flastname来自不同的行,这些行与数量和pname不相关。该查询应输出以下问题:在网站上找到销售每种产品最多的农民的姓名。
我有2个属性,即农民和购买者:
buys:
Fname;Flastname;pname;mname;maddress;amount;creditcard;
Cevdet;Sututan;Grain;Bim;Ilginc sk;18000;1230000000000010;
Cevdet;Sututan;Soy bean;Migros;Zengin Mh;5000;1230000000000050;
Halime;Sututan;Grain;Bim;Cikmaz Sk;1000;1230000000000340;
Muhammer;Kanzuk;Soy bean;Migros;Zengin Mh;34000;1230000000002400;
Gulden;Kanzuk;Grain;Tansas;Seftali Mh;1000;1230000000016810;
Gulden;Kanzuk;Soy bean;KIPA;Boyoz Sk;7000;1230000000117650;
farmers:
name;lastname;address;zipcode;city;phones;e-mails
Cevdet;Sututan;14 Cikmaz Sk;42050;Konya;5352223444;cevdet@sucu.com
Halime;Sututan;14 Cikmaz
Sk;42050;Konya;5356823445|5352223456;halime@sucu.com
Muhammer;Kanzuk;16 Genis
Sk;34052;Istanbul;5352223446;muhammer@sucu.com
Gulden;Kanzuk;16 Genis
Sk;34052;Istanbul;5352223447;gilden@sucu.com|gilden2@sucu.com
Murat;Kanzuk;16 Genis Sk;34052;Istanbul;5352223448;asd@sucu.com
expected output:
Grain;Hanedan;Gercek
Soy bean;Muhammer;Kanzuk
Rice;Behcet;Karci
Corn;Deniz;Suadiyeli
我的sql代码如下:
```
Select B.pname, B.Fname, B.Flastname, max(B.amount)
from buys B,
farmers F
where (B.Flastname=F.lastname and F.name = B.Fname)
group by B.pname ;
```
答案 0 :(得分:1)
在子查询中获取每种产品的最大金额,然后针对该查询进行合并
SELECT b.pname, Fname, Flastname, max_amount
FROM buys b
JOIN (SELECT pname, MAX(amount) AS max_amount FROM buys GROUP BY pname) m ON m.pname = b.pname AND m.max_amount = b.amount