我正在使用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
我是否有月份功能错误?
答案 0 :(得分:77)
我倾向于在输出中包含年份。一种方式:
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;
请记住订单,因为您可能想要按顺序排序,并且无法保证在分组后返回行的顺序。
答案 1 :(得分:12)
对于Oracle:
select EXTRACT(month from DATE_CREATED), sum(Num_of_Pictures)
from pictures_table
group by EXTRACT(month from DATE_CREATED);
答案 2 :(得分:0)
我正在MSSQL中这样做
获取每月数据:
@app.route('/upload', methods=['GET', 'POST'])
def index():
form = MyForm()
if request.method == 'POST':
if form.validate_on_submit():
blah blah blah I do something......
return redirect(url_for('index'))
return render_template('upload.html', form=form)
使用PIVOT获取每月数据:
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
答案 3 :(得分:-1)
对于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)
答案 4 :(得分:-2)
您可以使用:
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)