特定行的GROUP BY

时间:2017-09-22 12:10:37

标签: sql sql-server group-by

我有一个按人员分组的sql server结果。而SUMS是他们的日常数字和月度数据。

    Person  Team    Daily Figure    Month To Date
    Tony    Team 1          53              635
    Dan     Team 2         47               172
    Tom     Team 3         17               232
    Simon   Team 2          16              655
    Ben     Team 3         17               232
    Fred    Team 2          16              655

我如何仅仅通过团队2对这些结果进行分组?例如,我仍然希望显示其他个人结果,但我希望将第2组分组在一起。

示例结果

   Person   Team    Daily Figure    Month To Date
    Tony    Team 1          53              635
    Tom     Team 3         17               232
    Ben     Team 3         17               232
   Team 2   Team 2         79              1482

由于 UPDATE:

    SELECT 

     Person = case when Team = 'Team 2' 
     then 'Team 2' else Person  END,
     Team,
     SUM(ISNULL(Figure,0)) AS 'Daily Figure',
     SUM(Month To Date) AS 'Month To Date'

这是我的选择和错误

1 个答案:

答案 0 :(得分:8)

您可以在casePerson中使用select表达式group by

select 
    case when Team = 'Team 2' then 'Team 2' else Person end as Person
  , Team
  , sum([Daily Figure]) as [Daily Figure]
  , sum([Month To Date]) as [Month To Date]
from t
group by
    case when Team = 'Team 2' then 'Team 2' else Person end
  , Team

rextester演示:http://rextester.com/XHQ24032

返回:

+--------+--------+--------------+---------------+
| Person | Team   | Daily Figure | Month To Date |
+--------+--------+--------------+---------------+
| Tony   | Team 1 |           53 |           635 |
| Team 2 | Team 2 |           79 |          1482 |
| Ben    | Team 3 |           17 |           232 |
| Tom    | Team 3 |           17 |           232 |
+--------+--------+--------------+---------------+

如果您想使用cross apply()来避免重复case表达式:

select 
    x.Person
  , t.Team
  , sum(t.[Daily Figure]) as [Daily Figure]
  , sum(t.[Month To Date]) as [Month To Date]
from t
  cross apply (
    select case when t.Team = 'Team 2' then 'Team 2' else t.Person end as Person
    ) as x 
group by
    x.Person
  , t.Team

cross apply(values())

select 
    x.Person
  , t.Team
  , sum(t.[Daily Figure]) as [Daily Figure]
  , sum(t.[Month To Date]) as [Month To Date]
from t
  cross apply (values 
   (case when t.Team = 'Team 2' then 'Team 2' else t.Person end)
    ) as x (Person)
group by
    x.Person
  , t.Team