2014-03-25 52 views
2

我有一個記錄倉庫數據庫事務的表。本表中的信息包括交易發生地點,交易結束日期,結束時間,轉移數量和分部。我想獲得: - 任何單位和交易,爲每月每部這樣的:按月分組在SQL中顯示重複的月份

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 ....

+0

你可以給SQL來創建DW表,也可能是一些示例行嗎? –

回答

1

你被end_tran_date分組,而是要通過組強制t是該日期的月份部分。下面將潛在的工作:

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 
+0

這工作謝謝! – umvahed

0

GROUP BY子句需要指定數據應當按月和可能一年進行分組(儘管你不指定,我假設你不想進行交易不同年內彙總):

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語法更易於閱讀。

+0

這工作得很好,只是不得不玩格式,謝謝! – umvahed