2016-02-10 198 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