SQL如何获取按月发送的消息数

时间:2018-04-09 14:53:17

标签: sql sql-server tsql

我有一个发送消息的表,我想得到过去一年中逐月消息的总数。我是SQL的新手,所以我遇到了麻烦。我正在使用MSSQL 2012这是我的sql

SELECT sentDateTime, MessageID, status AS total, CONVERT(NVARCHAR(10), sentDateTime, 120) AS Month
FROM MessageTable
WHERE CAST(sentDateTime AS DATE) > '2017-04-01'
GROUP BY CONVERT(NVARCHAR(10), sentDateTime, 120), sentDateTime, MessageID, status
ORDER BY Month;

3 个答案:

答案 0 :(得分:4)

我认为month()year()函数比datepart()更方便。

我会选择:

select year(sentDateTime) as yr, month(sentDateTime) as mon, count(*)
from MessageTable
where sentDateTime > '2017-04-01'
group by year(sentDateTime), month(sentDateTime)
order by min(sentDateTime);

附加说明:

  • 仅包含您关注的select中的列。这将是定义月份和计数的那些。
  • 仅包含您关注的group by中的列。数据中找到的group by中表达式的每个组合都定义了一列。
  • 无需将sentDateTime明确转换为明确的日期进行比较。
  • order by按时间排序结果。使用min()是一个很好的方便。
  • 包括year()确保您不会犯错 - 比如将2018-04的数据与2017-04包含在一起。

答案 1 :(得分:1)

-- this selects the part of the date you are looking for, replace this with the date format you are using, this should give you what you are looking for
SELECT DATEPART(mm, GETDATE())

SELECT  COUNT(DATEPART(mm, sentDateTime)), MessageID, status
 From MessageTable where Cast(sentDateTime as date) > '2017-04-01'
 group by DATEPART(mm, sentDateTime), MessageID, status
 order by  DATEPART(mm, sentDateTime)

答案 2 :(得分:1)

您可以使用功能sentDateTime按月DATEPART(MONTH, sentDateTime)分组。如果没有为特定月份(total = 0)发送消息,则下一个选择也将产生结果。

;WITH PossibleMonths AS
(
    SELECT
        M.PossibleMonth
    FROM
        (VALUES 
            (1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11),(12)) M(PossibleMonth)
),
MonthTotals AS
(
    select  
        COUNT(1) AS Total,
        DATEPART(MONTH, sentDateTime) [Month] 
    From 
        MessageTable 
    where 
        Cast(sentDateTime as date) > '2017-04-01'
    group by 
        DATEPART(MONTH, sentDateTime)
)
SELECT
    P.PossibleMonth,
    Total = ISNULL(T.Total, 0)
FROM
    PossibleMonths AS P
    LEFT JOIN MonthTotals AS T ON P.PossibleMonth = T.Month