doudouchan5830 2015-05-06 11:48
浏览 171
已采纳

每组的最小值和最大值

I have two table

location:

  • location_id
  • address

itransfile:

  • id
  • transactionNumber
  • location_id
  • itemName
  • quantity

I want to get maximum and minimum sold items by locations.

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

The query I've done so far:

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

I don't know how will get max and min items from every group.

Sample Data:

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
  • 写回答

1条回答 默认 最新

  • duanpi7578 2015-05-06 12:34
    关注

    This is what you may be looking for if you need it in one query (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
    

    It looks for min/max values and then looks up the item name and location address. The GROUP_CONCAT makes sure that when there are more items with the same min/max quantity, you get all of them.

    Alternatively you can get rid of the GROUP BY and GROUP_CONCAT and get all the items in rows if you need to further process them.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序