多个选择今天,上周,上个月,本周

时间:2013-11-14 11:39:44

标签: sql sql-server

好的,所以我正在尝试为今天,上周,上个月和本周的表格中的每种消息类型创建一个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

enter image description here

*编辑*

Lolo发布结果 Results of post from Lolo

1 个答案:

答案 0 :(得分: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子句中添加日期过滤器。