sql月度分组_按月汇总SQL查询分组

本文讨论如何将存储小时级交易数据的Access 2007数据库转换为按月汇总视图。解决方案涉及到使用SQL查询,通过YEAR和MONTH函数对交易日期进行分组,以获取特定时间段(如2011年1月)的总使用量。
摘要由CSDN通过智能技术生成

I have a database of Transactions (Access 2007) that are recorded in hourly, daily and monthly intervals. I would like to view them in a meaningful way (instead of hour-by-hour energy usage, which is how it's stored, I want all usage for the month of January, 2011). The tables that I want to operate on have this general format:

CustID|CustomerCode|TransactionDate|(Transaction Hour depending on table)|Usage

So If I want to take a table like that and make a view that looked something like this

BillingPeriod|Usage(mWh)

1/2011 |500

2/2011 |600

3/2011 |700

etc

How would I go about doing that? The transaction dates can be any date, and the transaction hours can be 1-24. The query itself doesn't seem that hard, something along the lines of:

SELECT TransactionDate, SUM(Usage)

FROM UsageTable

Where (TransactionDate Between [Some Start Date] AND[Some End Date])

GROUP BY TransactionDate;

The problem is formatting. I obviously can't group by transactiondate for my desired results, I just wrote it so the query was semantically correct. Maybe I could do something like

SELECT Mid(TransactionDate,0,2) + Mid(TransactionDate, 6, 4)?

Any help would be appreciated

解决方案

It seems that you would need to group by both the month and the year. Otherwise, you'll have January 2010 and January 2011 combined:

SELECT YEAR(TransactionDate), MONTH(TransactionDate), SUM(Usage)

FROM YourTable

WHERE (TransactionDate Between [Some Start Date] AND[Some End Date])

GROUP BY YEAR(TransactionDate), MONTH(TransactionDate)

ORDER BY YEAR(Created), MONTH(Created)

I don't know if your version of SQL has the MONTH and YEAR functions, so you may have to use DATEPART.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值