在使用SQL时,我是一个新手,我想做的是仅使用月份和年份选择waterUsage和lectriccityUsage,然后从上一年中选择waterUsage和lectriccityUsage。
但是,我似乎无法找出使用日期的适当方法来完成这项工作。
表:每月帐单
1. billingDate 01-SEP-15 2. waterUsage varchar(256) 3. electrcityUsage varchar(256) 4. accountNumber varchar(256) select electrcityUsage, waterUsage from monthlyBill where accountNumber ='211' and billingDate = '12-12' /*,month, year*/
或者
select electrcityUsage, waterUsage from monthlyBill where accountNumber ='211' and billingDate = DATEADD(year,-1,GETDATE()); /*,previous year*/
一种选择是使用TO_CHAR:
TO_CHAR
select electrcityUsage, waterUsage from monthlyBill where accountNumber = '211' and to_char(billing_date, 'MM-YYYY') = '12-2012'
假设您实际上使用的是Oracle,而不是SQL Server。
如果需要2012,2011然后继续,然后在该WHERE子句中添加另一个条件。我可能EXTRACT在这种情况下使用:
2012
2011
WHERE
EXTRACT
select electrcityUsage, waterUsage from monthlyBill where accountNumber = '211' and extract(month from billingDate) = 12 and extract(year from billingdate) in (2011, 2012)