GROUP BY using parameters in SQL

前端 未结 4 1894
一整个雨季
一整个雨季 2020-12-19 11:01

I am trying to somehow group a report based on a drop-down list of parameters that is pre-defined. I want to be able to subtotal the Total Hours or Total Pay of my report b

4条回答
  •  隐瞒了意图╮
    2020-12-19 12:01

    I think you are fundamentally misunderstanding how GROUP BY works.

    GROUPING is a way to aggregate many rows together.

    If you return any fields not in the GROUP BY, you need to decide what to do with them. You can't NOT do anything with them because you could have multiple values per group. They must be either excluded or aggregated.

    To aggregate them, you need to decide what function to use (MAX, MIN, SUM, AVG, etc).

    If you want to show many rows, say one per employee, but want to include some information about totals for that employee's department, you need to use a subquery:

    SELECT employeeid, 
    FROM MyTable t
    INNER JOIN (SELECT DepartmentID, SUM(Totalhours) as TotHours...etc
                FROM SomeOtherTable
                GROUP BY DepartmentID) as Sub
      ON Sub.DepartmentID = t.departmentID
    

    There may be a way to do this dynamically but that is a pretty poor idea.

提交回复
热议问题