1

想象一下这是我表中的数据:

Amount/ Number /Type
100/ 1.2 / A
120 / 1.2 /A
130/ 1.1 / A
90 / 0.3 / A
50/ 2.4 / B
150 / 1.9 /B
150 / 1.9 / B

我希望这些数据分为两组,一组用于 A 型,一组用于 B 型。然后在这两组中,我希望它们按价格排序,一组升序,另一组降序。我可以这样做:

(SELECT * FROM `table` WHERE `type`='A' GROUP BY `number` LIMIT 10)
UNION ALL 
(SELECT * FROM `table` WHERE `type`='b' GROUP BY `number` LIMIT 15) ORDER BY `type`), 
(CASE WHEN `type`='A' THEN `number` END) ASC, 
(CASE WHEN `type`='B' THEN `number` END) DESC";

但是问题是我想将相同数字的类型相加。所以对于 1.2,我会得到 220/1.2/A,但是通过我的查询,我只会得到 100/1.2/A……我该如何加起来相同数量和相同类型的数量?

谢谢

4

3 回答 3

2

你在找这个吗?

SELECT SUM(amount) amount, number, type 
  FROM table1
 GROUP BY type, number
 ORDER BY type,
       CASE WHEN `type`='A' THEN `number` END ASC, 
       CASE WHEN `type`='B' THEN `number` END DESC;

输出:

| AMOUNT | NUMBER | TYPE |
--------------------------
|     90 |    0.3 |    A |
|    130 |    1.1 |    A |
|    220 |    1.2 |    A |
|     50 |    2.4 |    B |
|    300 |    1.9 |    B |

SQLFiddle

更新:如果您需要限制每种类型的源记录的数量,请使用它。请注意,当您使用时,LIMIT您必须明确说明ORDER BY,因为不保留行的顺序。

SELECT SUM(amount) amount, number, type 
FROM (
  (SELECT * FROM table1 WHERE type = 'A' ORDER BY number LIMIT 10)
  UNION ALL
  (SELECT * FROM table1 WHERE type = 'B' ORDER BY number LIMIT 15)
  ) q
 GROUP BY type, number
 ORDER BY type,
       CASE WHEN `type`='A' THEN `number` END ASC, 
       CASE WHEN `type`='B' THEN `number` END DESC;

SQLFiddle

于 2013-05-18T22:03:04.557 回答
1

这是您想要的查询:

(SELECT sum(amount) as amount, number, type
 FROM `table`
 WHERE `type`='A'
 GROUP BY `number` LIMIT 10
)
UNION ALL 
(SELECT sum(amount) as amount, number, type
 FROM `table`
 WHERE `type`='b'
 GROUP BY `number` LIMIT 15
)
ORDER BY `type`, 
          (CASE WHEN `type`='A' THEN `number` END) ASC, 
          (CASE WHEN `type`='B' THEN `number` END) DESC;

注意:这将返回 10 行 A 和 15 行 B之后group by我猜这就是你真正想要的。

此外,group by将自动按number. 如果您想要随机顺序,group by rand()请在limit.

于 2013-05-18T22:19:36.403 回答
0

大概是这样的?

select Number,Type,sum(Amount) from x group by Number,Type
+--------+------+--------+
| Number | Type | sum(a) |
+--------+------+--------+
|    0.3 | A    |     90 |
|    1.1 | A    |    130 |
|    1.2 | A    |    220 |
|    1.9 | B    |    300 |
|    2.4 | B    |     50 |
+--------+------+--------+
5 rows in set (0.00 sec)
于 2013-05-18T22:10:00.367 回答