這嚇我一跳! 得到了以下數據:來自SUM的MySQL MAX
+----+-----+-------+------------+
| 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 {編輯0001} ::還有一個額外的領域,也必須用於過濾數據,稱之爲{TYPE},一個可以讓「單」或' MULTIPLE'作爲價值。
我想爲每個{ID}的SUM(每個不同的{REG})得到最大值。很明顯,這是一個簡單的表示形式,表格最多可達64985928個寄存器,{DATE}是過濾數據。
這將是第一步得到的總和每個{REG}:
+----+------+
| 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米stucked:
+----+------+
| 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 |
+---------+-------------+
你讀過「有」嗎? – 7alhashmi
考慮提供一個sqlfiddle – Strawberry