我有两张桌子
位置:
itransfile:
我希望按地点获得最高和最低销售商品。
HighestItemName HighQauntity LowestItemName LowQuantity LocationName
Chicken Burger 50 Tako 5 Gulshan
Chicken Burger 100 Tikka 10 Nipa
Pasta 150 Cheese Burger 12 Liyari
Pizza 200 Chicken Burger 3 F.B.Area
我到目前为止所做的查询:
SELECT t.itemName as HighestItemName, sum(t.quantity) as HighQuantity, l.address LocationName
from itransfile as t join locations as l
on t.location_id = l.location_id
where t.location_id IN(1,2,3,4)
group by t.location_id
我不知道如何从每个群组中获取max
和min
个项目。
示例数据:
ID TransNumber ItemName Quantity location_id
1 1234 Chicken Burger 3 1
2 1234 Cheese Burger 1 1
3 1235 Sandwich 4 2
4 1332 Salad 1 4
5 14537 Tikka 1 3
6 1236 Roll 3 2
7 1333 Biryani 2 4
location_id address
1 Gulshan
2 Nipa
3 Liyari
4 F.B.Area
答案 0 :(得分:1)
如果您在一个查询(SQLFiddle)中需要它,那么这就是您可能正在寻找的内容:
select
l.address,
imax.itemName max_item, max_min.max_q,
imin.itemName min_item, max_min.min_q
FROM
(select
i.location_id, MAX(i.quantity) max_q, MIN(i.quantity) min_q
FROM
itransfile i
GROUP BY
i.location_id) as max_min
LEFT JOIN itransfile imax ON (max_min.max_q = imax.quantity)
LEFT JOIN itransfile imin ON (max_min.min_q = imin.quantity)
LEFT JOIN location l ON (max_min.location_id = l.location_id)
GROUP BY
l.location_id
查找最小/最大值,然后查找项目名称和位置地址。 GROUP_CONCAT
确保当有更多项目具有相同的最小/最大数量时,您将获得所有这些项目。
或者,如果您需要进一步处理它们,可以删除GROUP BY
和GROUP_CONCAT
并获取行中的所有项目。