检索子查询的多个和列

时间:2017-01-19 16:21:06

标签: sql sql-server reporting-services

来自此查询:

    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

我无法检索两个“最后状态”的总和。我所有的结果是我的两列空。提前谢谢。

1 个答案:

答案 0 :(得分: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)