SQL计数行和内部联接

时间:2017-01-19 13:19:48

标签: sql-server count report inner-join builder

我有这个问题:

select s.LastState
      ,count(s.LastState) as sumS
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
group by s.LastState

这将返回两个州的数量,我希望得到两个总和。

目前,我看到我的第一行是让我们承认

我的ID X的10状态1和5状态2

我希望看到15(两个州的计数总和)。

1 个答案:

答案 0 :(得分:0)

select --s.LastState
      LastState='LastState1and2'
      , count(s.LastState) as sumS
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
--group by s.LastState