GROUP BY问题

时间:2010-12-11 11:39:38

标签: sql-server group-by

我有一个名为Users:

的SQL Server 2005表
UserID | Date        | Name | Issues | On    | Off   | Value
1      | 02/02/2010  | John | 3      | True  | False | 75
2      | 07/23/2010  | Nate | 7      | False | True  | 50
3      | 02/12/2010  | John | 5      | False | True  | 45
4      | 01/29/2010  | John | 8      | True  | False | 65
5      | 09/01/2010  | Nate | 6      | True  | False | 30
6      | 12/07/2010  | John | 2      | False | True  | 40
7      | 07/18/2010  | Nate | 10     | True  | False | 80

我希望得到每个名称的问题的总和,当On为真时,值为SUM,在给定日期之间,当Off为真时,值的和为:

Name | No of issues| SUM of ON | SUM of OFF
John | 18          | 140       | 85
Nate | 23          | 110       | 50

谢谢!

3 个答案:

答案 0 :(得分:2)

试试这个:

SELECT
    Name, 
    SUM(issues),
    SUM(CASE [On] WHEN 1 THEN Value ELSE 0 END) 'Sum ON',
    SUM(CASE [On] WHEN 0 THEN Value ELSE 0 END) 'Sum OFF'
FROM 
    dbo.testuser
GROUP BY
    Name

这确实给了我你提到的所需输出。

答案 1 :(得分:0)

以下应该可以解决问题:

SELECT Users.[NAME], 
       SUM(Users.Issues) As Issues, 
       SUM(CASE WHEN Users.[On] THEN Users.[Value] ELSE 0 END) AS On, 
       SUM(Case WHEN Users.[Off] THEN Users.[Value] ELSE 0 END) As Off 
FROM Users 
GROUP BY Users.[NAME]

答案 2 :(得分:0)

通常,在表中找不到两列,一列称为ON,另一列称为OFF,因为它们通常是互斥状态,两列允许两者都为True。通常,您只需要一个名为ON的列,可以将其设置为False以指示关闭状态。所以你的桌子上发生的事情并不是很清楚。

如果On和Off确实是相互排斥的状态而你只是以愚蠢的方式完成事情,那么进入状态为on-state和off-state的行的最佳方法是使用UNION。

           select {desired columns for rows that are on), sum(value) as YourSum
           where on=true
           group by  {group-by column(s)}
           UNION
           select {desired columns for rows that are off}, sum(value) as YourSum
           where off=true
           group by {group-by column(s)}

您还可以创建两个持久视图,一个用于On行,另一个用于Off Rows,UNION选择它们。

如果您想要使用上述UNION方法的单独列,您可以创建虚拟列,子查询,并通过伪聚合MAX()函数提供总和:

          select name, max( OnSum) as OnSummed, max( OffSum) as OffSummed from
          (

          select name, sum(value) as OnSum, 0 as OffSum
          from mytable
          where on= true
          group by name
          union
          select name, 0 as OnSum, sum(value) as OffSum
          from mytable
          where off=true
          group by name

          )
          group by name