在IIF()中嵌入MAX()函数?

时间:2013-12-31 16:45:22

标签: sql ms-access aggregate-functions iif

我在select语句中嵌套了IIF()个函数,并在每个嵌套MAX()内部嵌套了SELECT d2s_loader_performance_tbl.employee_id, IIF(d2s_loader_performance_tbl.wk_ending_dt=max(d2s_loader_performance_tbl.wk_ending_dt),"Last Wk", IIF(d2s_loader_performance_tbl.wk_ending_dt=max(d2s_loader_performance_tbl.wk_ending_dt)-7,"2 Wks Ago", IIF(d2s_loader_performance_tbl.wk_ending_dt=max(d2s_loader_performance_tbl.wk_ending_dt)-14,"3 Wks Ago", IIF(d2s_loader_performance_tbl.wk_ending_dt=max(d2s_loader_performance_tbl.wk_ending_dt)-21,"4 Wks Ago")))), d2s_loader_performance_tbl.hrs_worked, d2s_loader_performance_tbl.move_count, d2s_loader_performance_tbl.moves_per_hour FROM d2s_loader_performance_tbl WHERE d2s_loader_performance_tbl.wk_ending_dt In ( SELECT DISTINCT TOP 4 wk_ending_dt FROM d2s_loader_performance_tbl ORDER BY wk_ending_dt DESC) GROUP BY d2s_loader_performance_tbl.employee_id, d2s_loader_performance_tbl.move_count, d2s_loader_performance_tbl.moves_per_hour 个函数。它似乎要我在GROUP BY中包含这个select语句。这是我的疑问:

{{1}}

当我运行时,我收到此错误:“您尝试执行不包含指定表达式的查询[列出嵌套IIF的块]作为聚合函数的一部分。当我将其放入GROUP时BY(没有意义),我得到这个错误:“GROUP BY子句中不能有聚合函数”

那么H-E双曲棍球棒的进入是否需要我做什么?关键在于将周结束日期转换为相对期限。此报告每周更新一次,我厌倦了手动浏览所有查询和报告以及更改对新日期的引用。

谢谢!

1 个答案:

答案 0 :(得分:4)

如何将查询的一部分放入子选择(或者甚至是单独的查询)。像这样:

SELECT 
  orig.employee_id, 
  IIF(orig.wk_ending_dt=PreAgg.max_wk_ending_dt),"Last Wk",
    IIF(orig.wk_ending_dt=PreAgg.max_wk_ending_dt)-7,"2 Wks Ago",
      IIF(orig.wk_ending_dt=PreAgg.max_wk_ending_dt)-14,"3 Wks Ago",
        IIF(orig.wk_ending_dt=PreAgg.max_wk_ending_dt)-21,"4 Wks Ago")))),
  orig.hrs_worked, 
  orig.move_count, 
  orig.moves_per_hour
FROM (
  SELECT 
  d2s_loader_performance_tbl.employee_id, 
  max(d2s_loader_performance_tbl.wk_ending_dt) AS Max_wk_ending_dt

  FROM d2s_loader_performance_tbl

  GROUP BY 
  d2s_loader_performance_tbl.employee_id
) PreAgg JOIN d2s_loader_performance_tbl AS orig ON
PreAgg.employee_id=orig.employee_id

WHERE orig.wk_ending_dt In (
  SELECT DISTINCT TOP 4 wk_ending_dt 
  FROM d2s_loader_performance_tbl
  ORDER BY wk_ending_dt DESC)