如何按派生列进行分组

时间:2014-10-31 17:17:27

标签: sql sql-server

我有这个SQL:

   Select Hours, LastName, FirstName, UUID, 
      Case 
         When DatePart(WeekDay, Date) = 1 Then
            Date - 6
         Else
            Date - DatePart(Weekday, Date) + 2
         End as [Week]
   From Entry
   Where Date between '06/30/2014' and '10/31/2014'

我想要做的是将我使用Case语句创建的[Week]列进行分组。这是可能的,如果是这样,我该怎么做呢?

谢谢!

2 个答案:

答案 0 :(得分:2)

您无法按SQL Server中的列别名进行分组 - 您需要按表达式进行分组:

Select Hours, LastName, FirstName, UUID, 
  Case 
     When DatePart(WeekDay, Date) = 1 Then
        Date - 6
     Else
        Date - DatePart(Weekday, Date) + 2
     End as [Week]
From Entry
Where Date between '06/30/2014' and '10/31/2014'
GROUP BY
  Case 
     When DatePart(WeekDay, Date) = 1 Then
        Date - 6
     Else
        Date - DatePart(Weekday, Date) + 2
     End

虽然您可以使用子查询使其更清晰:

SELECT * FROM
   (
   Select Hours, LastName, FirstName, UUID, 
      Case 
         When DatePart(WeekDay, Date) = 1 Then
            Date - 6
         Else
            Date - DatePart(Weekday, Date) + 2
         End as [Week]
    From Entry
    Where Date between '06/30/2014' and '10/31/2014'
    )
    GROUP BY [Week]

但在任何一种情况下,您都需要决定如何聚合组表达式中 not 的值。 Hours做一笔总结是有道理的,但你如何汇总名称和ID?如果不需要聚合,只需将它们排除在结果之外:

SELECT Week, SUM(Hours) FROM
   (
   Select Hours, LastName, FirstName, UUID, 
      Case 
         When DatePart(WeekDay, Date) = 1 Then
            Date - 6
         Else
            Date - DatePart(Weekday, Date) + 2
         End as [Week]
    From Entry
    Where Date between '06/30/2014' and '10/31/2014'
    )
    GROUP BY [Week]

答案 1 :(得分:1)

我猜您正在尝试找到员工的max or sum小时数。所以这样的事情可以帮助你。请记住,没有聚合函数的列应该存在于group by中。

SELECT Max(Hours),-- sum(Hours)
       LastName,
       FirstName,
       UUID,
       CASE
         WHEN Datepart(WeekDay, Date) = 1 THEN Date - 6
         ELSE Date - Datepart(Weekday, Date) + 2
       END AS [Week]
FROM   Entry
WHERE  Date BETWEEN '06/30/2014' AND '10/31/2014'
GROUP  BY LastName,
          FirstName,
          UUID,
          CASE
            WHEN Datepart(WeekDay, Date) = 1 THEN Date - 6
            ELSE Date - Datepart(Weekday, Date) + 2
          END