2

此查询工作正常,但看起来多余(也许我错了)。是否存在更好的方法来做到这一点?(我需要所有 4 列以及每一行的总数)

 select parz.*, (parz.sessioniSvolte + parz.sessioniPianificate ) as sessioniTotale
 from (
    select 
      e.Prefettura AS Prefettura, 
      count(case when  s.Giorno<getDate() then    s.idSessione else null end) AS sessioniSvolte,
      count(case when  s.Giorno>=getDate() then    s.idSessione else null end) AS sessioniPianificate
        from SESSIONE_FORMAZIONECIVICA s
        inner join SEDE_SESSIONECIVICA e ON e.idSede = s.idSede

        GROUP BY e.Prefettura
) as parz

我建立了类似的问题,但它们与我的问题不匹配。

4

1 回答 1

3

您的查询可以通过添加一个简单的不子查询来重写count(*)

select 
  e.Prefettura AS Prefettura, 
  count(case when s.Giorno<getDate() then s.idSessione end) AS sessioniSvolte,
  count(case when s.Giorno>=getDate() then s.idSessione end) AS sessioniPianificate,
  count(*) as sessioniTotale
from SESSIONE_FORMAZIONECIVICA s
join SEDE_SESSIONECIVICA e ON e.idSede = s.idSede
GROUP BY e.Prefettura

我删除了多余的else null,因为 null 是不匹配时的默认结果。

于 2013-10-22T09:30:27.603 回答