Add values ​​according to date

I have the following table where I want the Quantity_Sold value to be added for the product and the Customer if the item has been invoiced more than once in the same month. and I want to get this amount of the number of values ​​sold per month in a separate column

Item   Customer         Invoice_Date         Quantity_Sold
 A        XX      2014-11-04 00:00:00.000         13
 A        XX      2014-11-21 00:00:00.000         23
 A        XX      2014-12-19 00:00:00.000        209
 A        YY      2014-12-01 00:00:00.000         10
 A        YY      2014-12-22 00:00:00.000          6
 B        XX      2014-10-29 00:00:00.000        108
 B        YY      2014-11-06 00:00:00.000         70
 B        YY      2014-11-24 00:00:00.000         84

EX: XX billed A twice in November, so I would like to get 36 (13 + 23) in a separate column.

So I need a result table,

Item   Customer          Invoice_date         Sum_Qty_Invoiced
A         XX               2014-Nov                  36
A         XX               2014-Dec                 209
A         YY               2014-Dec                  16
B         XX               2014-Oct                 108   
B         YY               2014-Nov                 154 

great if anyone can help me with this thanks

+4
source share
3 answers

This is a simple group with some string manipulations in a column Invoice_Date.

SELECT
  Item,
  Customer,
  CAST(Year(Invoice_Date) AS VARCHAR(4)) + '-' + LEFT(DateName(m,Invoice_Date),3) AS Invoice_Date,
  SUM(Quantity_Sold) AS Sum_Qty_Sold
FROM MyTable
GROUP BY Item,
  Customer,
  CAST(Year(Invoice_Date) AS VARCHAR(4)) + '-' + LEFT(Datename(m,Invoice_Date),3)

: http://www.sqlfiddle.com/#!6/8fea75/3

+4

GroupBy.

Item,Customer,CAST(YEAR(Invoice_Date) AS Varchar(4))+'-'+LEFT(DATENAME(m,Invoice_Date),3)

:

SELECT Item, Customer, 
     CAST(YEAR(Invoice_Date) AS Varchar(4)) +'-'+
       LEFT(DATENAME(m,Invoice_Date),3)
         AS Invoice_Date,SUM(Quantity_Sold)
         AS Sum_Qty_Invoiced FROM TableName GROUP BY Item,Customer, 
       Item,Customer,CAST(YEAR(Invoice_Date) AS Varchar(4))+'-
     '+LEFT(DATENAME(m,Invoice_Date),3)
0

You can achieve this using the DatePart and DateName functions of SQL Server.

SELECT Item
    , Customer
    , CONVERT (CHAR(4), DATEPART(YEAR, Invoice_date)) + '-' + CONVERT(CHAR(3), DATENAME(MONTH, Invoice_date)) AS Invoice_date
    , SUM(Quantity_Sold) AS Sum_Qty_Invoiced
FROM [dbo].[Table1]
GROUP BY DATEPART(YEAR, Invoice_date), DATENAME(MONTH, Invoice_date), Item, Customer
0
source

All Articles