如何在分组

时间:2015-11-19 16:15:30

标签: sql case aggregate-functions

我有一个数据集,我想按客户代码进行分组,对于每个代码,我想在一个月的日期之间汇总交易总数,并让每个月成为一个单独的列。我可以使这个动态我主要关注的是构建初始选择以根据需要输出数据。

我有什么:

SELECT [cmasterno]
    ,CASE 
        WHEN Month([dtrs]) = 1
            AND Year([dtrs]) = YEAR(GETDATE())
            THEN SUM([nftrsamt])
        END AS 'Jan 2014'
    ,CASE 
        WHEN Month([dtrs]) = 2
            AND Year([dtrs]) = YEAR(GETDATE())
            THEN SUM([nftrsamt])
        END AS 'Feb 2014'
FROM [AccountMate].[dbo].[gltrsn]
WHERE csource LIKE 'AR'
    AND cacctid LIKE '%4220%'
GROUP BY cmasterno

数据样本将是

cmasterno   dtrs    ntrsamt
CEN01-A    1/24/2014    -22.2
AUT129-A    2/24/2014   -0.84
CEN01-A    1/22/2014    -19.86
CEN01-A    2/22/2014    -13.2
AUT129-A    1/22/2014   -18.42
AUT129-A    1/22/2014   -1
AUT129-A    2/22/2014   -316.56
CEN01-A    2/21/2014    -2.04

2 个答案:

答案 0 :(得分:2)

使用条件SUM

SELECT [cmasterno],
       SUM (CASE 
               WHEN Month([dtrs]) = 1 AND Year([dtrs]) = YEAR(GETDATE())
                    THEN [nftrsamt]
               ELSE 0
            END
           ) AS 'Jan 2014',
       SUM (CASE 
               WHEN Month([dtrs]) = 2 AND Year([dtrs]) = YEAR(GETDATE())
                    THEN [nftrsamt]
               ELSE 0
            END
           ) AS 'Feb 2014'
FROM [AccountMate].[dbo].[gltrsn]
WHERE csource LIKE 'AR'
    AND cacctid LIKE '%4220%'
GROUP BY cmasterno

答案 1 :(得分:1)

要完成,你也可以使用连接

SELECT [cmasterno], sum(jan.nftrsamt) as 'Jan 2014', sum(feb.nftrsamt) as 'Feb 2014'
FROM [AccountMate].[dbo].[gltrsn] b
LEFT JOIN [AccountMate].[dbo].[gltrsn] jan on b.cacctid = jan.cacctid and Month(jan.[dtrs]) = 1 AND Year(jan.[dtrs]) = YEAR(GETDATE())
LEFT JOIN [AccountMate].[dbo].[gltrsn] feb on b.cacctid = feb.cacctid and Month(feb.[dtrs]) = 2 AND Year(feb.[dtrs]) = YEAR(GETDATE())
WHERE csource LIKE 'AR' AND cacctid LIKE '%4220%'
GROUP BY cmasterno

根据您的索引,连接可以比案例快得多。那是O(1)而不是O(N)