这是我的查询
SELECT q2.item_code
, q2.SELL_DELIVERY_AMOUNT
, q2.count_amount
FROM
( SELECT i.item_code
, s.SELL_DELIVERY_AMOUNT
, count(s.SELL_DELIVERY_AMOUNT) count_amount
FROM sell_delivery_items s
, items i
WHERE s.item_id = i.item_id
GROUP
BY SELL_DELIVERY_AMOUNT
, item_code
) q2
order
by item_code
, count_amount desc
,结果是
item_code SELL_DELIVERY_AMOUNT count_amount
0001 50 2
0001 100 1
0002 150 3
我需要为每个item_code组仅显示最高count_amount行。 我已经完成了对某些答案的搜索,但仍然不适用于我的。
这是我想要的结果
item_code SELL_DELIVERY_AMOUNT count_amount
0001 50 2
0002 150 3
我该怎么做?谢谢你的回答。
答案 0 :(得分:0)
这是未经测试的,因为我没有MySQL - 但这样的事情应该有效:
SELECT q2.item_code, q2.SELL_DELIVERY_AMOUNT, q2.count_amount
FROM
(SELECT i.item_code, s.SELL_DELIVERY_AMOUNT , count(s.SELL_DELIVERY_AMOUNT) as count_amount
FROM sell_delivery_items s , items i, @rownum := @rownum + 1 AS rank
WHERE s.item_id = i.item_id
GROUP BY SELL_DELIVERY_AMOUNT, item_code) as q2
where rank = 1
order by item_code, count_amount desc
您需要向内部查询添加“排名”或“行号”功能,然后向外部查询添加过滤器以仅选择排名最高的行。
以下是MySQL中排名的另一个例子:Ranking by Group in MySQL
答案 1 :(得分:0)
这个怎么样?
SELECT q2.item_code, q2.SELL_DELIVERY_AMOUNT, max(q2.count_amount)
FROM
(SELECT i.item_code, s.SELL_DELIVERY_AMOUNT , count(s.SELL_DELIVERY_AMOUNT) as count_amount
FROM sell_delivery_items s , items i
WHERE s.item_id = i.item_id
GROUP BY SELL_DELIVERY_AMOUNT, item_code) as q2
group by q2.item_code
order by count_amount desc
在这里order by item_code, count_amount desc
,您按自然顺序排序item_code
,a< z,所以它不需要,因为它是由group by
订购的。
答案 2 :(得分:0)
我已经找到了解决方案。这是我的:
SELECT q3.item_code, q3.item_name, substring_index(q3.AMOUNT_LIST, ',' , 1) as most_amount_count,
substring_index(q3.count_list,',',1) as count_time from
(SELECT q2.item_code, q2.item_name, GROUP_CONCAT(SELL_DELIVERY_AMOUNT ORDER BY q2.count_amount DESC) as AMOUNT_LIST,
GROUP_CONCAT(q2.count_amount ORDER BY q2.count_amount desc) as count_list from
(SELECT i.item_code, i.ITEM_NAME, s.SELL_DELIVERY_AMOUNT , count(s.SELL_DELIVERY_AMOUNT) as count_amount
FROM sell_delivery_items s , items i
WHERE s.item_id = i.item_id
GROUP BY SELL_DELIVERY_AMOUNT, item_code
order by item_code, count_amount desc
) as q2
group by q2.item_code )as q3