MySQL组通过查询附加行

时间:2012-11-09 09:39:11

标签: mysql sql

我有一张名为trades

的表格
traders   qty

abc      50000
xyz      35000
pqr      25000
xxx      10000
yyy      20000
uuu      15000
abc      2000
xyz      3000
pqr      1500 

我需要将前三名数量明智的交易者和所有其他交易者分开。

SELECT trader,SUM(qty)
FROM traders
GROUP BY trader DESC
LIMIT 3

从上面的查询我可以得到如下的答案

tr        qty

abc      52000
xyz      38000
pqr      26500

但我的要求如下

tr        qty

abc      52000
xyz      38000
pqr      26500
other    45000   ----- with this column for all other traders except the largest 3

2 个答案:

答案 0 :(得分:3)

尝试此查询 -

SELECT
  IF(t2.trader IS NULL, 'other', t1.trader) trader,
  SUM(qty) qty
FROM traders t1
  LEFT JOIN (
  SELECT trader, SUM(qty) FROM traders
    GROUP BY trader
    ORDER BY SUM(qty) DESC
    LIMIT 3) t2
  ON t1.trader = t2.trader
GROUP BY trader
ORDER BY IF(t2.trader IS NULL, 1, 0), qty DESC

+--------+-------+
| trader | qty   |
+--------+-------+
| abc    | 52000 |
| xyz    | 38000 |
| pqr    | 26500 |
| other  | 45000 |
+--------+-------+

答案 1 :(得分:2)

这是另一个:

(select trader, sum(qty)
 from trades
 group by trader
 order by sum(qty) desc
 limit 3)
union
(select 'other', sum(qty)
 from (select trader, sum(qty) qty
       from trades
       group by trader
       order by sum(qty) desc
       limit 3, 4000000000) t);

SQL Fiddle可以玩。