按月分组显示SQL中的重复月份

时间:2014-03-25 18:02:13

标签: sql sql-server date transactions group-by

我有一个记录Warehouse DB事务的表。此表中的信息包括交易发生的位置,交易结束的日期,结束的时间,转移的数量以及分部。我想得到: - 每个部门每月的单位和交易数量如下:

Division Month Transactions Units
1 January 5 10 1 February 10 11 2 February 5 10

我的SQL查询如下:

SELECT
    DISTINCT  tranl.Division, 
    DATENAME(month,tranl.trandate) AS 'Month',
    COUNT(tranl.qty) AS Transactions,
    SUM(tranl.qty) AS Units
FROM translog (nolock) tranl 
WHERE tranl.location = 'stage' 
AND end_tran_date >= '2013-04-01 00:00:00.000' 
GROUP BY end_tran_date, tranl.Division
ORDER BY  tranl.Division

但我得到了不同的结果:

Division Month Transactions Units 1 January 5 10 1 January 3 22 2 February 10 40 2 February 3 12 2 March 1 1 ....

2 个答案:

答案 0 :(得分:1)

您按end_tran_date进行分组,但您希望仅按该日期的月份分组。以下内容可能有效:

select 
    DISTINCT  tranl.Division, 
    DATENAME(month,tranl.trandate) as 'Month',
     COUNT(tranl.qty) as TRANSACTIONS,
     SUM(tranl.qty) as UNITS
    from translog (nolock) tranl 
    where tranl.location = 'stage' 
   and end_tran_date >= '2013-04-01 00:00:00.000' 
   GROUP BY DATENAME(month,tranl.trandate), tranl.Division
   ORDER BY  tranl.Division

答案 1 :(得分:0)

GROUP BY条款需要指定数据应按月和可能的年份进行分组(尽管您没有指定,我假设您没有' ; t希望聚合不同年份的交易):

SQL Server 2012

SELECT
    DISTINCT tranl.division,
    FORMAT(end_tran_date, 'yyyy-MM', 'en-us') AS Month,
    Count(tranl.qty) AS Transactions,
    Sum(tranl.qty) AS Units     
FROM
    translog (nolock) tranl      
WHERE
    tranl.location = 'stage'             
    AND end_tran_date >= '2013-04-01 00:00:00.000'      
GROUP  BY
    tranl.division,
    FORMAT(end_tran_date, 'yyyy-MM', 'en-us')      
ORDER  BY
    tranl.division

SQL Server 2008

SELECT
    DISTINCT tranl.division,
    CONVERT(VARCHAR(7), end_tran_date, 120) AS Month,
    Count(tranl.qty) AS Transactions,
    Sum(tranl.qty) AS Units     
FROM
    translog (nolock) tranl      
WHERE
    tranl.location = 'stage'             
    AND end_tran_date >= '2013-04-01 00:00:00.000'      
GROUP  BY
    tranl.division,
    CONVERT(VARCHAR(7), end_tran_date, 120)      
ORDER  BY
    tranl.division

如果您可以使用,我认为使用FORMAT的SQL Server 2012语法比格式化日期的神秘CONVERT语法更容易阅读。