0

好的,所以我正在尝试为今天、上周、上个月和本周的表中的每种消息类型创建一个 TSQL 结果集。不同的消息类型是 101,103,202。

以下 sql 产生我需要的输出,但我不知道如何根据三种消息类型过滤结果。

Select distinct
  ( Select Count(*) from MsgDateDetail
      Where convert(date,MsgDate,103) = Convert(date,GETDATE())
And SenderBIC = @senderbic) As Today,
  ( Select Count(*) from MsgDateDetail
      Where MsgDate Between DATEADD(dd, -(DATEPART(dw, GetDate())-1)-7, GetDate())
      And DATEADD(dd, 7-(DATEPART(dw, GetDate()))-7, GetDate())
      And SenderBIC = @senderbic) As LastWeek,
  ( Select Count(*) FROM MsgDateDetail
      Where convert(date,MsgDate,103) = (DATEADD(mm,-1, Convert(date,GETDATE())))
And SenderBIC = @senderbic) AS LastMonth,
  ( Select Count(*) from MsgDateDetail
      Where MsgDate between (DATEADD(week, DATEDIFF(week,0,GETDATE()),-1)) AND getDate()
      And SenderBIC = @senderbic) AS ThisWeek
FROM MsgDateDetail h1

在此处输入图像描述

*编辑 *

发布来自 Lolo 的结果 洛洛发帖结果

4

1 回答 1

1

尝试这个:

SELECT
    MsgType,

    SUM(CASE WHEN CONVERT(DATE, MsgDate, 103) = 
                  CONVERT(DATE, GETDATE()) 
             THEN 1 ELSE 0 END) As Today,

    SUM(CASE WHEN CONVERT(DATE, MsgDate, 103) BETWEEN 
                  DATEADD(DD, -(DATEPART(DW, GETDATE())-1)-7, GETDATE()) AND DATEADD(DD, 7-(DATEPART(DW, GETDATE()))-7, GETDATE()) 
             THEN 1 ELSE 0 END) As LastWeek,

    SUM(CASE WHEN DATEADD(DD, -DATEPART(DD, CONVERT(DATE, MsgDate, 103)) + 1, CONVERT(DATE, MsgDate, 103)) = 
                  DATEADD(MM, -1, DATEADD(DD, -DATEPART(DD, GETDATE()) + 1, CONVERT(DATE, GETDATE())))
             THEN 1 ELSE 0 END) As LastMonth,

    SUM(CASE WHEN CONVERT(DATE, MsgDate, 103) BETWEEN 
                  DATEADD(WEEK, DATEDIFF(WEEK,0,GETDATE()),-1) AND GETDATE() 
             THEN 1 ELSE 0 END) As ThisWeek
FROM 
    MsgDateDetail
WHERE
    SenderBIC = @senderbic

GROUP BY
    MsgType

MsgType每个使用组获得一行。我还修改了计算计数的方式——在我的解决方案中,没有可以加快速度的子查询。此外,您可能希望在 where 子句中添加日期过滤器。

于 2013-11-14T12:05:55.907 回答