根据日期添加值

时间:2015-02-23 08:44:02

标签: sql sql-server

我有下表,如果项目在同一个月内已多次开票,我希望为项目和客户添加Quantity_Sold值。我希望在单独的列中获得每月销售数量的总和

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已于11月两次开具物品A的发票,因此我希望在另一栏中获得36(13 + 23)。

所以我喜欢的结果表是

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 

很棒,如果有人可以帮我这个 感谢

3 个答案:

答案 0 :(得分:4)

这是一个简单的组,在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

答案 1 :(得分:0)

它是一个简单的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)

答案 2 :(得分:0)

您可以使用SQL Server的DatePart和DateName函数来实现此目的。

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