MONTH将查询结果分组为T-SQL

时间:2015-12-09 09:50:41

标签: sql-server tsql

我正在寻找提示MONTH和WindowsAccount如何分组我的查询结果,其中月份信息来自查询中的InsertedAt列。如果有人能提到如何实现这一点,我将感激不尽。 提前感谢你。

 SELECT InsertedAt,
       TaskName,
       WindowsAccount,
       Start,
       Round (Time / 60.1, 2) AS Time
FROM   (SELECT CONVERT (VARCHAR(23), InsertedAt, 104) AS InsertedAt,
               Subject,
               TaskName,
               WindowsAccount,
               CONVERT (VARCHAR(23), NewStart, 104)   AS Start,
               Datediff("MINUTE", OldStart, OldEnd)   AS OldDiff,
               Datediff("MINUTE", NewStart, NewEnd)   AS Time
        FROM   History
        WHERE  ( Month(InsertedAt) IN ( 9, 10, 11 )
                 AND Year(InsertedAt) = 2015 )) AS Tab
WHERE  Tab.OldDiff <> Tab.Time
ORDER  BY InsertedAt,
          WindowsAccount

1 个答案:

答案 0 :(得分:0)

您可以使用DatePart功能进行分组。

作为示例(https://msdn.microsoft.com/en-us/library/ms177673.aspx):

SELECT DATEPART(m,OrderDate) AS N'Month'
    ,SUM(TotalDue) AS N'Total Order Amount'
FROM Sales.SalesOrderHeader
GROUP BY DATEPART(m,OrderDate)
ORDER BY DATEPART(m,OrderDate);