简体   繁体   English

SQL Server:按月,年和分组方式计算数据

[英]Sql Server: Calculate data by each month,year and Group by something

First of all, my table structure is something similar like this: 首先,我的表结构类似于以下内容:

CREATE TABLE Testing(
       [ID]        NVARCHAR(50),
       [DATE]      DATETIME,
       [TOTAL]     INT,
       [ITEM]      NVARCHAR(50),
       [Warehouse] NVARCHAR(50)
)ON[PRIMARY]

I put some sample here: 我在这里放了一些样本:

[ID] [Date]      [Total] [Item] [Warehouse]
1    2011-04-04  400     A0001   B12
2    2011-05-04  500     A0001   B13
3    2011-04-30  400     A0001   B12
4    2011-04-25  400     A0001   B13
5    2011-06-05  600     A0001   B12
6    2011-03-02  300     A0001   B11
7    2011-05-28  500     A0001   B13   

I am trying to group by [Item] and [Warehouse] and [Date] by month as well For example output: 我也尝试按[商品]和[仓库]和[日期]按月份分组。例如,输出:

The result should be like this 结果应该是这样的

[Date]        [Total]   [Item]  [Warehouse]
March 2011     300       A0001   B11
April 2011     800       A0001   B12
June 2011      500       A0001   B12
April 2011     400       A0001   B13
May 2011       1000      A0001   B13

I tried the sql something like, that i parse in month and year part to made the selection 我尝试了类似的sql,我在月份和年份部分中进行了解析以进行选择

SELECT [Item],[Warehouse],SUM(Total) AS Total
FROM [Testing]
WHERE Datepart(month,[Date]) = 4 AND DATEPART(year,[Date]) = 2011
GROUP BY [Item],[Warehouse]

I get the expected result?Is there any way to do? 我得到了预期的结果吗,有什么办法吗? i actually trying to came out a close balance for each month and year by distinct of warehouse and item? 我实际上试图通过不同的仓库和物料来实现每月和每年的收支平衡?

Sound to me its need to loop through a prefix table.. Its that anyway to do so? 在我看来,它需要遍历前缀表。无论如何,这样做吗?

Thanks 谢谢

Regards Liangck 问候梁克

Have a look at the following functions 看一下以下功能

DATENAME (Transact-SQL) and DATEPART DATENAME(Transact-SQL)DATEPART

Have a look at the example below 看下面的例子

DECLARE @Table TABLE(
        DateValue DATETIME
)

INSERT INTO @Table SELECT '01 Jan 2011'
INSERT INTO @Table SELECT '01 Feb 2011'
INSERT INTO @Table SELECT '01 Feb 2011'

SELECT  DATENAME(month,DateValue) + ' ' + CAST(DATEPART(year,DateValue) AS VARCHAR(4)),
        COUNT(1) TotalCnt
FROM    @Table
GROUP BY DATENAME(month,DateValue) + ' ' + CAST(DATEPART(year,DateValue) AS VARCHAR(4))

Results: 结果:

February 2011   2
January 2011    1

I think that formatting date on SQL Server side is (usually) a bed idea, but anyway you can try: 我认为在SQL Server端格式化日期(通常)是一个床主意,但是无论如何您都可以尝试:

select datename(mm, dateadd(m, datediff(m, 0, [date]), 0)) + ' ' +
      select cast(datepart(yy, dateadd(m, datediff(m, 0, [date]), 0)) as varchar)
      [date] sum(total) as total, item,warehouse
from testing
group by item, warehouse, dateadd(m, datediff(m, 0, [date]), 0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM