2013-12-12 63 views
0

如何獲得結果而無需分組?選擇不分組

我的表

id user_id amount currency_id type status 
5 2 2.00 1 0 0 
6 3 3.00 1 0 0 
4 1 1.00 1 0 0 
7 4 4.00 1 0 0 
8 5 3.00 1 1 0 

我做了以下選擇

SELECT id, user_id, amount, currency_id, SUM(amount) 
FROM market 
WHERE amount <=3 
AND type = 0 
AND status = 0 

結果:

id user_id amount currency_id SUM(amount) 
5 2 2.00 1 6.00 

如何得到這樣的結果:

id user_id amount currency_id SUM(amount) 
5 2 2.00 1 0 6.00 
6 3 3.00 1 0 6.00 
4 1 1.00 1 0 6.00 
+0

如果您不想使用GROUP,請不要使用SUM()。你是否試圖獲得查詢中所有記錄的總和?我想我沒有看到每行的'6.00'來自哪裏。 –

回答

1

如果你的目的是用來返滿足此條件,總結個人記錄他們並沒有真正需要SUM值作爲每一行的字段(不知道爲什麼你會),那麼我會建議看看GROUP BY ... WITH ROLLUP修飾符。它的工作原理是這樣的:

SELECT id, user_id, SUM(amount) AS `amounts`, currency_id 
FROM market 
WHERE amount <=3 
AND type = 0 
AND status = 0 
GROUP BY id WITH ROLLUP 

在這裏,我通過id分組,因爲這將保持個人記錄不變,因爲該值是唯一的

你的輸出應該是這樣的:

id user_id amounts currency_id 
5  2  2.00 1 
6  3  3.00 1 
4  1  1.00 1 
NULL 3  6.00 1 

注最後一條記錄提供了對SUM()函數的彙總。另請注意,彙總行中的user_idcurrency_id的值是不確定的,因爲它們不是GROUP BY或聚合的一部分。因此,它們沒有意義。

0

在這裏你去:

SELECT id, user_id, amount, currency_id, t2.total 
FROM market, (
    SELECT SUM(amount) AS total 
    FROM market 
    WHERE amount <=3 
    AND type = 0 
    AND status = 0 
) AS t2 
WHERE amount <=3 
AND type = 0 
AND status = 0 
1

你可以做加盟

SELECT id, 
     user_id, 
     amount, 
     currency_id, 
     a.totalAmount 
FROM market 
     CROSS JOIN 
     (
      SELECT SUM(amount) totalAmount 
      FROM market 
      WHERE amount <=3 
        AND type = 0 
        AND status = 0 
     ) a 
WHERE amount <=3 
     AND type = 0 
     AND status = 0 

或使用內聯子查詢,

SELECT id, 
     user_id, 
     amount, 
     currency_id, 
     (
      SELECT SUM(amount) totalAmount 
      FROM market 
      WHERE amount <=3 
        AND type = 0 
        AND status = 0 
     ) totalAmount 
FROM market 
WHERE amount <=3 
     AND type = 0 
     AND status = 0 
+0

哪個更好? – Dream