SQL Server - 按月排列选择查询结果

时间:2014-10-22 16:17:51

标签: sql sql-server ssms

我有以下查询(以及其他一些非常类似的查询),它们收集大量数据(在本例中为调用),然后按月排列。

它工作正常并输出我需要的结果,但我觉得必须有一个更实用/更短的方法:

SELECT
 sum(case when datepart(mm,calldate) = '1' THEN 1 ELSE 0 END) AS 'JAN',
 sum(case when datepart(mm,calldate) = '2' THEN 1 ELSE 0 END) AS 'FEB',
 sum(case when datepart(mm,calldate) = '3' THEN 1 ELSE 0 END) AS 'MAR',
 sum(case when datepart(mm,calldate) = '4' THEN 1 ELSE 0 END) AS 'APR',
 sum(case when datepart(mm,calldate) = '5' THEN 1 ELSE 0 END) AS 'MAY',
 sum(case when datepart(mm,calldate) = '6' THEN 1 ELSE 0 END) AS 'JUN',
 sum(case when datepart(mm,calldate) = '7' THEN 1 ELSE 0 END) AS 'JUL',
 sum(case when datepart(mm,calldate) = '8' THEN 1 ELSE 0 END) AS 'AUG',
 sum(case when datepart(mm,calldate) = '9' THEN 1 ELSE 0 END) AS 'SEP',
 sum(case when datepart(mm,calldate) = '10' THEN 1 ELSE 0 END) AS 'OCT',
 sum(case when datepart(mm,calldate) = '11' THEN 1 ELSE 0 END) AS 'NOV',
 sum(case when datepart(mm,calldate) = '12' THEN 1 ELSE 0 END) AS 'DEC'

 FROM [Telephony].[dbo].[tbl_Outbound]

 WHERE source like '132%'
       and duration > 300

   union all

SELECT
 sum(case when datepart(mm,calldate) = '1' THEN 1 ELSE 0 END) AS 'JAN',
 sum(case when datepart(mm,calldate) = '2' THEN 1 ELSE 0 END) AS 'FEB',
 sum(case when datepart(mm,calldate) = '3' THEN 1 ELSE 0 END) AS 'MAR',
 sum(case when datepart(mm,calldate) = '4' THEN 1 ELSE 0 END) AS 'APR',
 sum(case when datepart(mm,calldate) = '5' THEN 1 ELSE 0 END) AS 'MAY',
 sum(case when datepart(mm,calldate) = '6' THEN 1 ELSE 0 END) AS 'JUN',
 sum(case when datepart(mm,calldate) = '7' THEN 1 ELSE 0 END) AS 'JUL',
 sum(case when datepart(mm,calldate) = '8' THEN 1 ELSE 0 END) AS 'AUG',
 sum(case when datepart(mm,calldate) = '9' THEN 1 ELSE 0 END) AS 'SEP',
 sum(case when datepart(mm,calldate) = '10' THEN 1 ELSE 0 END) AS 'OCT',
 sum(case when datepart(mm,calldate) = '11' THEN 1 ELSE 0 END) AS 'NOV',
 sum(case when datepart(mm,calldate) = '12' THEN 1 ELSE 0 END) AS 'DEC'

  FROM [Telephony].[dbo].[tbl_Outbound]

  WHERE source like '132%'

感谢您提供的任何提示:)

1 个答案:

答案 0 :(得分:1)

我相信以下内容可行。这使用SQL Server的Pivot功能:

SELECT rowName,[January],[February],[March],[April],[May],[June],[July],[August],[September],[October],[November],[December] 
FROM (
    SELECT
        "Duration>300" as rowName,
        datename(month, calldate) as MonthName,
        Count(*) as recordCount

    FROM
        [Telephony].[dbo].[tbl_Outbound]
    WHERE source like '132%'
        and duration > 300
    UNION ALL
    SELECT
        "AllDurations" as rowName,
        datename(month, calldate) as MonthName,
        Count(*) as recordCount

    FROM
        [Telephony].[dbo].[tbl_Outbound]
    WHERE source like '132%'
) as SourceTable
PIVOT
(
    Sum(recordCount)
    FOR MonthName in ([January],[February],[March],[April],[May],[June],[July],[August],[September],[October],[November],[December])
) AS PivotTable