58

我正在使用 Oracle SQL Developer。我基本上有一个包含列的图片表:

[DATE_CREATED(日期),NUM_of_PICTURES(int)]

如果我选择 *,我会得到类似的输出:

01-May-12    12
02-May-12    15
03-May-12    09
...
...
01-Jun-12    20
...
etc.

我正在尝试将这些图片总和汇总为每月而不是每天。

我试过做类似的事情:

select Month(DATE_CREATED), sum(Num_of_Pictures))
from pictures_table
group by Month(DATE_CREATED);

这会输出一个错误:

ORA-00904: "MONTH": invalid identifier
00904. 00000 -  "%s: invalid identifier"
*Cause:    
*Action:
Error at Line: 5 Column: 9

我的月份功能有误吗?

4

5 回答 5

125

我倾向于将年份包括在输出中。单程:

select to_char(DATE_CREATED, 'YYYY-MM'), sum(Num_of_Pictures)
from pictures_table
group by to_char(DATE_CREATED, 'YYYY-MM')
order by 1

另一种方式(更标准的 SQL):

select extract(year from date_created) as yr, extract(month from date_created) as mon,
       sum(Num_of_Pictures)
from pictures_table
group by extract(year from date_created), extract(month from date_created)
order by yr, mon;

请记住 order by,因为您可能希望这些按顺序排列,并且无法保证在 group by 之后返回行的顺序。

于 2012-07-17T23:53:47.803 回答
17

对于甲骨文:

select EXTRACT(month from DATE_CREATED), sum(Num_of_Pictures)
from pictures_table
group by EXTRACT(month from DATE_CREATED);
于 2012-07-17T22:37:53.347 回答
0

我在 MSSQL 中这样做

获取月度数据:

 SELECT YEAR(DATE_CREATED) [Year], MONTH(DATE_CREATED) [Month], 
     DATENAME(MONTH,DATE_CREATED) [Month Name], SUM(Num_of_Pictures) [Pictures Count]
    FROM pictures_table
    GROUP BY YEAR(DATE_CREATED), MONTH(DATE_CREATED), 
     DATENAME(MONTH, DATE_CREATED)
    ORDER BY 1,2

使用 PIVOT 获取月度数据:

SELECT *
FROM (SELECT YEAR(DATE_CREATED) [Year], 
       DATENAME(MONTH, DATE_CREATED) [Month], 
       SUM(Num_of_Pictures) [Pictures Count]
      FROM pictures_table
      GROUP BY YEAR(DATE_CREATED), 
      DATENAME(MONTH, DATE_CREATED)) AS MontlySalesData
PIVOT( SUM([Pictures Count])   
    FOR Month IN ([January],[February],[March],[April],[May],
    [June],[July],[August],[September],[October],[November],
    [December])) AS MNamePivot
于 2020-12-15T05:39:07.947 回答
-2

对于 MS SQL,您可以这样做。

    select  CAST(DATEPART(MONTH, DateTyme) as VARCHAR) +'/'+ 
CAST(DATEPART(YEAR, DateTyme) as VARCHAR) as 'Date' from #temp
    group by Name, CAST(DATEPART(MONTH, DateTyme) as VARCHAR) +'/'+
 CAST(DATEPART(YEAR, DateTyme) as VARCHAR) 
于 2015-05-15T16:30:11.997 回答
-3

您可以使用:

    select FK_Items,Sum(PoiQuantity) Quantity  from PurchaseOrderItems POI
    left join PurchaseOrder PO ON po.ID_PurchaseOrder=poi.FK_PurchaseOrder
    group by FK_Items,DATEPART(MONTH, TransDate)
于 2016-02-11T11:46:40.740 回答