Search code examples
sql-servercountreportinner-joinbuilder

SQL Count Lines and Inner join


I have this query :

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

This returns the number of both state and I'd like to have the sum of both my counts.

Currently I see my first line with let's admit

10 state 1 and 5 state 2 for my ID X

and I'd like to see 15 (sum of counts for both states).


Solution

  • 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