2014-01-28 64 views
2

我有一個表,結構是這樣的:查詢來獲取最小查詢數據費用

BID_FK    AccountID   Amount 
    1     1-1-1-1-1-1-1  4050 
    1     1-1-1-1-1-1-1  4050 
    1     1-1-1-1-1-1-1  4050 
    1     1-1-1-1-1-1-1  4050 
    1     1-1-1-1-1-1-2  500 
    1     1-1-1-1-1-1-2  500 
    1     1-1-1-1-1-1-2  500 
    1     1-1-1-1-1-1-2  500 
    2     1-1-1-1-1-1-1  6580 
    2     1-1-1-1-1-1-1  6580 
    2     1-1-1-1-1-1-1  6580 
    2     1-1-1-1-1-1-1  6580 
    2     1-1-1-1-2-1-1  1000 
    2     1-1-1-1-2-1-1  1000 
    2     1-1-1-1-2-1-1  1000 
    2     1-1-1-1-2-1-1  1000 

我想查詢失控把這樣的:

AccountID   Amount(BID_FK = 1)  Amount (BID_FK = 2) 
1-1-1-1-1-1-1  16200     26320 
1-1-1-1-1-1-2  2000     0 
1-1-1-1-2-1-1  0      4000 

用最小的查詢費用,因爲我有大量的數據。

任何幫助將不勝感激!

回答

2

也許這樣的事情可以幫助嗎?

SELECT 
AccountID, 
SUM(CASE WHEN BID_FK=1 THEN Amount ELSE 0 END) AMOUNT1, 
SUM(CASE WHEN BID_FK=2 THEN Amount ELSE 0 END) AMOUNT2 
FROM yourtable 
GROUP BY AccountId 
2
SELECT AccountID, 
     SUM(CASE WHEN BID_FK=1 THEN Amount ELSE 0 END) AS `Amount(BID_FK = 1)` 
     SUM(CASE WHEN BID_FK=2 THEN Amount ELSE 0 END) AS `Amount(BID_FK = 2)` 
FROM yourTable 
GROUP BY AccountID 
+0

嗯,我必須upvote這一個:D –

+0

+1給你先生以及.. –