2016-02-10 195 views
0

我有兩個臨時表(下面),第一個標記是五個條件之一。第二個從該表中拉出並基於該狀況進行總計和計數。我怎麼能得到第二個表格來處理這個或類似的格式?sql select語句select sum where

select ID 
    ,sum_value  
    ,condition_field 
    ,'condition_1' = case when condition_type in (1,2) then 1 else 0 end 
    ,'condition_2' = case when condition_type in (3,4) then 1 else 0 end 
    --etc... 
into #temp  
from my_table 

select ID 
    ,sum_value 
    ,'1_amt' = SUM(sum_value) from #temp where condition_1 = 1 
    ,'1_cnt' = COUNT(ID) from #temp where condition_1 = 1 
    ,'2_amt' = SUM(sum_value) from #temp where condition_2 = 1 
    ,'2_cnt' = COUNT(ID) form #temp where condition_2 = 2 
from #temp 
+0

這甚至工作? –

+0

什麼是MySQL或SQL Server?你不能在兩者中使用相同的代碼。 –

+0

第一個查詢是,但第二個查詢不是,我'1_amt'子查詢後得到語法錯誤 – waterguard

回答

1

你想要更多的東西是這樣的:

SUM(CASE WHEN condition_1=1 THEN sum_value ELSE 0 END) AS 1_amt