这吓坏了我! 得到以下数据:
+----+-----+-------+------------+
| ID | REG | VALUE | DATE |
+----+-----+-------+------------+
| 1 | 1A | 100 | 2009-01-01 |
| 1 | 1A | 100 | 2009-02-01 |
| 1 | 1A | 100 | 2009-03-01 |
| 2 | 1B | 100 | 2009-01-01 |
| 2 | 1B | 100 | 2009-02-01 |
| 2 | 1B | 100 | 2009-03-01 |
| 2 | 1C | 100 | 2009-01-01 |
| 2 | 1C | 100 | 2009-02-01 |
| 2 | 1C | 200 | 2009-03-01 |
+----+-----+-------+------------+
PS {edit 0001} ::还有一个额外的字段,也必须用于过滤数据,称之为{TYPE},可以将'SINGLE'或'MULTIPLE'作为值。
我想在每个{ID}的SUM(每个不同的{REG})之间获得MAX。显然,这是一个简单的表示,表达到了64985928个寄存器,{DATE}是过滤数据。
那将是第一步获得每个{REG}的SUM:
+----+------+
| ID | SUM |
+----+------+
| 1 | 300 |
| 2 | 300 |
| 2 | 400 |
+----+------+
那是:
SELECT
SUM(value)
FROM
table
WHERE
(date BETWEEN '2009-01-01' AND '2009-03-01')
GROUP BY
reg;
然后,从每个SUM中获取MAX,这是我被困的地方:
+----+------+
| ID | MAX |
+----+------+
| 1 | 300 |
| 2 | 400 |
+----+------+
我试过了:
SELECT
a.id,
MAX(b.sum)
FROM
table a,
(SELECT
SUM(b.value)
FROM
table b
WHERE
(b.date BETWEEN '2009-01-01' AND '2009-03-01') AND (a.id = b.id)
GROUP BY
b.reg);
有什么想法吗? PS:对不起错误。
PS {edit 0002} 要复制原始查询和数据,这样可能会有所帮助。
$ QUERY:
SELECT
clienteid AS "CLIENTE",
SUM(saldo) AS "SUMA"
FROM
etl.creditos
WHERE
(titularidad_tipo LIKE 'TITULAR')
AND
(mes_datos BETWEEN '2008-11-01' AND '2009-10-01')
GROUP BY
nuc
ORDER BY
clienteid;
GOT:
+---------+-------------+
| CLIENTE | SUMA |
+---------+-------------+
| 64 | 1380690.74 |
| 187 | 1828468.71 |
| 187 | 2828102.80 |
| 325 | 26037422.21 |
| 389 | 875519.05 |
| 495 | 20084.93 |
| 495 | 109850.46 |
+---------+-------------+
然后,我正在寻找的是:
+---------+-------------+
| CLIENTE | MAX |
+---------+-------------+
| 64 | 1380690.74 |
| 187 | 1828468.71 |
| 325 | 26037422.21 |
| 389 | 875519.05 |
| 495 | 109850.46 |
+---------+-------------+
但是跑步:
SELECT
clienteid AS "CLIENTE",
MAX(suma)
FROM
(SELECT clienteid, SUM(saldo) AS "suma" FROM etl.creditos
WHERE (mes_datos BETWEEN '2009-08-01' AND '2009-10-01') AND (titularidad_tipo LIKE 'TITULAR')
GROUP BY clienteid, nuc) AS sums
GROUP BY
clienteid
ORDER BY
clienteid;
结果为:
+---------+-------------+
| CLIENTE | SUMA |
+---------+-------------+
| 64 | 336879.21 |
| 187 | 1232824.51 |
| 325 | 3816173.62 |
| 389 | 218423.83 |
| 495 | 34105.99 |
+---------+-------------+
答案 0 :(得分:9)
SELECT ID, MAX(reg_sum)
FROM
(
SELECT ID, SUM(value) AS reg_sum FROM table
WHERE (date BETWEEN '2009-01-01' AND '2009-03-01')
GROUP BY ID, reg
) a GROUP by ID
答案 1 :(得分:2)
您可以添加[按SUM(值)DESC限制1的顺序]以获取查询结果的最大值。
SELECT SUM(value) as maxcount FROM table WHERE (date BETWEEN '2009 01-01' AND '2009-03-01') GROUP BY reg order by maxcount desc limit 1;