Select statement to return sum by year

  • I am working on a query to show a sum of costs by year in a vendor purchase table. the final output I am trying to achieve will show the Vendor Number, Vendor Name, Year, Total Sum.

    Below is a sample table.

    CREATE TABLE [dbo].[tempVendorPurchases]

    (

    [VendorNum] [INT] NOT NULL,

    [Amount] [int] NOT NULL,

    [PostingDate] [Date] NOT NULL,

    [VendorName] [varchar](20) NOT NULL,

    )

    GO

    insert into [dbo].[tempVendorPurchases]

    (

    [VendorNum],[Amount], [PostingDate], [VendorName]

    )

    Values

    ( '1234', '100', '2012-01-15', 'SoftwareCo')

    ,( '1234', '10000', '2013-02-15', 'SoftwareCo')

    ,( '1234', '12500', '2011-02-15', 'SoftwareCo')

    ,( '1234', '15300', '2012-03-15', 'SoftwareCo')

    ,( '1234', '13450', '2011-08-15', 'SoftwareCo')

    ,( '1234', '10150', '2012-05-15', 'SoftwareCo')

    ,( '1234', '18000', '2013-06-15', 'SoftwareCo')

    Select * from [dbo].[tempVendorPurchases];

    The end result would look like the below set.

    Vendor Number Vendor Name Year TotalSum

    1234 SoftwareCo 2011 25950

    1234 SoftwareCo 2012 25550

    1234 SoftwareCo 2013 28000

    Any suggestions are welcome. Thanks.

  • I haven't tested this with your ssample data, but I think this will give you the result:

    SELECT

    [VendorNum]

    , [VendorName]

    , YEAR([PostingDate]) as 'Year'

    , Sum([Amount]) as 'TotalSum'

    FROM [tempVendorPurchases]

    GROUP BY

    [VendorNum]

    , [VendorName]

    , YEAR([PostingDate])

    ** Don't mistake the ‘stupidity of the crowd’ for the ‘wisdom of the group’! **
  • Just what I needed. Thanks HanShi!

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply