查询以最小的查询成本获取数据

时间:2014-01-28 12:01:09

标签: sql sql-server-2008 sql-server-2012

我有一张表,结构如下:

   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 个答案:

答案 0 :(得分: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

答案 1 :(得分: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