这把我吓坏了!得到以下数据:
+----+-----+-------+------------+
| 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}将复制原始查询和数据,因此可能会有所帮助。
$查询:
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;
拿到:
+---------+-------------+
| 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 |
+---------+-------------+