2

I have a data set that I would like to group by a customer code and for each code I would like to Sum transaction totals between the dates of a month and have each month become a separate column. I can make this dynamic my main concern is structuring the initial select to out put the data as desired.

What I have:

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

A sample of the data would be

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
Juan Carlos Oropeza
  • 47,252
  • 12
  • 78
  • 118
Allen Craig
  • 127
  • 10

2 Answers2

2

Use conditional 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
Juan Carlos Oropeza
  • 47,252
  • 12
  • 78
  • 118
1

Just to be complete you can do this with joins too

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

Depending on your indexes a join can be much faster than a case. That is O(1) and not O(N)

Hogan
  • 69,564
  • 10
  • 76
  • 117