【问题标题】:Retrieve multiple sum columns of sub queries检索子查询的多个总和列
【发布时间】:2017-01-19 16:21:05
【问题描述】:

从这个查询:

    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”条件的总和。结果我的两列都是空的。提前致谢。

【问题讨论】:

  • 您是如何尝试检索总和列的?
  • table2的意义是什么?此查询中未使用它。你为什么需要它?此外,您应该在 Where 子句中的 OR 语句周围加上 ()

标签: sql sql-server reporting-services


【解决方案1】:

我不确定您为什么在此查询中做一些未使用的事情,例如您的子查询中的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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-08
    • 2020-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多