Domanda

I have nested IIF() functions in my select statement, and inside of each a nested MAX(). It seems to want me to include this select statement in the GROUP BY. Here is my query:

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

When I run, I get this error: "You tried to execute a query that does not include the specified expression [lists the chunk that is the nested IIFs] as part of an aggregate function. When I put this in the GROUP BY (which doesn't make sense), I get this error: "Cannot have aggregate function in GROUP BY clause"

So what in the H-E-double hockey sticks does access want me to do? The point of this is turning week-ending dates into a relative term. This report gets updated weekly, and I am tired of manually going through all my queries and reports and changing the references to new dates.

Thank you!

È stato utile?

Soluzione

How about putting part of your query into a sub-select (or maybe even a separate query). Like this:

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)
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top