2010-10-08 57 views
0

投票表如何編寫合計總價值SQL查詢特定條件

PK_ID ob_type ob_id VOTE user_id VOTED_ON 
    1  100  1  1 NISHANT 02/08/10 
    2  100  1  1  DEVI 02/08/10 
    3  100  1  1 VIRENDRA 02/08/10 
    4  100  1  0  XYZ 02/08/10 
    5  200  1  1  XCXCX 02/08/10 
    6  200  1  1  CXC 03/02/11 
    7  200  1  0  XCCX 03/02/11 
    8  200  1  0  XCCX 03/02/11 
    9  300  1  1 XCCXXC 03/02/11 
    10  300  1  1  XCCX 03/02/11 
    11  300  1  1  SD 02/08/10 
    12  300  1  0 XCCXXCC 02/08/10 
    13  400  4  0 CXXCXC 02/08/10 
    14  400  4  0  XCCX 03/02/11 
    15  400  4  0  CXC 03/02/11 
    16  400  1  1  CXC 03/02/11 

在這裏我要計算在一個特定的對象類型和id的投票總沒有。

SELECT 
    COUNT (ALL [PK_ID]) AS [TOTAL_VOTE], 
    COALESCE (
     (SELECT 
       [IS_THUMBS_UP] 
      FROM 
       [votetable] 
      WHERE 
       [ob_type] = 400 AND 
       [ob_id] = 4 AND 
       [FK_VOTED_BY] = Nishant),-1) AS [MY_VOTING] 
    FROM 
    [votetable] 
    WHERE 
    [ob_type] = 400 AND 
    [ob_id] = 4 

這給結果

總票數= 4 和我的票= 0

但這裏有表決權總爲-2(BCZ 3個假(0)和1真)

那麼如何獲得正確的價值。

+0

顯示的數據中沒有行,其ob_id爲4.哪個錯誤 - 數據或預期結果? – 2010-10-08 08:07:12

+0

我真的不明白你是如何得到任何結果的,如果你僅限於那些'ob_type = 100和ob_id = 4' – Dexter 2010-10-08 08:08:39

+0

先生現在我編輯你可以看到.. – 2010-10-08 08:11:35

回答

1

我建議(SQLServer的語法):

select sum(case [VOTE] when 1 then 1 else -1 end) as total_votes, 
     sum((case [VOTE] when 1 then 1 else -1 end) * 
      (case when [user_id] = @username then 1 else 0) as user_votes 
from [votetable] 
where [ob_type] = @obtype and [ob_id] = @obid 

@username,@obtype和@obid是與所需的用戶名,對象類型和對象ID變量。