如何使用月份中的日期按月获取一些列值

时间:2017-02-17 08:27:58

标签: sql sql-server-2008 c#-4.0

目前我有这张桌子:

---------------------------------
date        | value1 | value2 |
-----------------------------------
01-01-2017  |  20    | 10 
02-01-2017  |  30    | 10
03-01-2017  |  40    | 20
01-02-2017  |  50    | 5
02-02-2017  |  10    | 15
03-02-2017  |  10    | 20

我需要这个输出:

Date      | Value1| Value2|
-------------------------
Jan-2017  | 90   |  40
Feb-2017  | 70   |  40

有人可以请我提供适当的查询吗?

3 个答案:

答案 0 :(得分:0)

您希望按日期部分Year-Month进行分组,并获得value1value2的总和。这是通过以下方式实现的:

SELECT CONVERT(VARCHAR(7), DATE, 20) DATE
    ,SUM(value1) Value1
    ,SUM(value2) Value2
FROM myTable
GROUP BY CONVERT(VARCHAR(7), DATE, 20)

如果您想显示月份而不是数字,请尝试以下方法:

SELECT FORMAT( date,'MMM yyyy') DATE
    ,SUM(value1) Value1
    ,SUM(value2) Value2
FROM myTable
GROUP BY FORMAT( date,'MMM yyyy')

答案 1 :(得分:0)

选择DATE_FORMAT(日期,'%b-%Y')作为日期,值1,值2来自(选择月份(日期),总和(值1)值1,总和(值2)值2,年份(日期) ),测试日期 按月(日期),年(日期)分组aa

答案 2 :(得分:0)

这对2008年没问题

WITH CTE AS (
           SELECT  
           SUBSTRING(CAST(DATENAME(MM, DATE) AS VARCHAR(15)), 1, 3) 
           + '-' +
           CAST(DATEPART(YY, DATE) AS VARCHAR(4)) AS Date, DATEPART(MM, Date) AS MonthOrder,
           Value1 ,   
           Value2
           FROM tblTestTableDates
           )

 SELECT Date, SUM(Value1) AS Value1 , SUM(Value2) AS Value2
    FROM CTE
    GROUP BY Date , MonthOrder
    ORDER BY MonthOrder

CTE看起来更干净,没有它的另一种方法

SELECT CONVERT(VARCHAR(3), DATENAME(MM, DATE)) + '-' +
 CAST(DATEPART(YY, DATE) AS VARCHAR(4)), 
SUM(Value1) AS Value1, 
SUM(Value2) AS Value2
 FROM tblTestTableDates
 GROUP BY CONVERT(VARCHAR(3), DATENAME(MM, DATE)) + '-' + CAST(DATEPART(YY,DATE) AS VARCHAR(4)), DATEPART(MM, DATE)
 ORDER BY DATEPART(MM, DATE)