同时计算多个平均命令

Compute Multiple Average Commands Simultaneously

这是对类似 post...

的后续

我有以下看起来像这样的数据集。我只想 select 那些 ESITwoToFive 变量为“1”的人,然后计算每个唯一日期的 AVG total_ED_LOS。我也想对 ESIFourFive 变量做同样的事情。

ID  CheckinDate  ESITwoToFive ESIFourFive   Total_ED_Los   
 1   Feb 7             1            0             23
 2   Feb 7             0            1             23
 3   Feb 7             1            0             28
 4   Feb 8             1            0             43
 5   Feb 8             1            0             83
 6   Feb 8             0            1             29
 7   Feb 8             0            1             32
 8   Feb 9             1            0             93
 9   Feb 9             1            0             77
 10  Feb 9             0            1             33

我得到了以下代码,用于计算 ESITwoToFive 变量,该代码有效。

 select t.checkin_date, avg(t.total_ed_los) as [Avg LOS]
 from [Fast Track Quality Research ESI Levels] t
 where t.esitwotofive = 1
 group by t.checkin_date

期望的输出:

  Checkindate             Avg LOS for ESITwoToFive  Avg LOS for ESIFourFive
  Feb 7                   24                               23
  Feb 8                   54                               30
  Feb 9                   86                               56

尝试使用 IIf() 条件表达式:

SELECT t.checkin_date, Avg(IIf(ESITwoToFive=1,t.total_ed_los,Null)) AS [AvgLOStwo],
Avg(IIf(ESIFourFive=1,t.total_ed_los,Null)) as [AvgLOSfour]
FROM [Fast Track Quality Research ESI Levels] t
GROUP BY t.checkin_date

条件可能是最干净的解决方案,但只是提供一个没有条件的替代方案:

select 
    t.checkin_date,
    sum(t.total_ed_los * t.esitwotofive) / sum(t.esitwotofive),
    sum(t.total_ed_los * t.esifourfive)  / sum(t.esifourfive),
from
    [Fast Track Quality Research ESI Levels] t
group by
    t.checkin_date