2017-01-19 5 views
0

を照会します。は、サブの複数の和の列を取得し、このクエリから

select LastStateS='LastStateS1and2' 
     , count(s.LastState) as sumS, 
    LasteStateE='LastStateE1and2' 
     , count(e.LastState) as sumE 
from table1 t1 
    join table2 t2 
     on t1.ID = t2.ID 
    join (select LastState 
       ,count(LastState) as sum 
      from table1 
      where ID = X 
      and LastState = 1 
      or LastState = 2 
      group by LastState 
     ) s 

     on s.LastState = t1.LastState 
    join (select LastState 
       ,count(LastState) as sum 
      from table1 
      where ID = X 
      and LastState = 3 
      or LastState = 4 
      group by LastState 
     ) e 

     on e.LastState = t1.LastState 

私は両方の私の「laststate」状態の合計を取得することはできません。私が結果として持っているのは、私の2つの列が空であることだけです。前もって感謝します。

+1

どのように合計列を取得しようとしましたか? –

+1

'table2'の意義は何ですか?このクエリでは使用されません。なぜあなたはそれが必要なのですか?また、 'Where'節の' OR'文の周りに '()'を置くべきです。 –

答えて

0

サブクエリでcount(LastState)のように、このクエリで使用されていないものがいくつあるのかわかりません。サブクエリのために参加し、あなたは左を使用する

select 
     LastStateS ='1 and 2' 
    , countS = sum(case when t1.LastState in (1,2) then 1 else 0 end) 
    , LasteStateE ='3 and 4' 
    , countE = sum(case when t1.LastState in (3,4) then 1 else 0 end) 
    from table1 t1 
    inner join table2 t2 on t1.id = t2.id and t1.id = X 

あなたの元のクエリは、あなたが望む結果を返すために取得する必要があります:

私は、これはあなたが探している結果を得るために必要なすべてだと思います

select 
    LastStateS='LastStateS1and2' 
    , count(s.LastState) as sumS 
    , LasteStateE='LastStateE1and2' 
    , count(e.LastState) as sumE 
from table1 t1 
    inner join table2 t2 on t1.ID = t2.ID 
    left join (
    select 
     LastState 
     , count(LastState) as sum 
     from table1 
     where ID = X 
     and LastState = 1 
     or LastState = 2 
     group by LastState 
    ) s 
    on s.LastState = t1.LastState 
    left join (
    select 
     LastState 
     , count(LastState) as sum 
     from table1 
     where ID = X 
     and LastState = 3 
     or LastState = 4 
     group by LastState 
    ) e 
    on e.LastState = t1.LastState 

また@WEI_DBAが彼らのコメントで指摘するように、あなたがwhere ID = X and LastState = 3 or LastState = 4 代わりのwhere ID = X and (LastState = 3 or LastState = 4)を使用してから予期せぬ結果をもたらす可能性がある、注意してください。

関連する問題