2012-12-17 64 views
0
String sql= "select amount,\n"+ "Temperature,\n"+ "Density\n"+ 
    "from sheet\n"+ "where Code=? and product=? and and month(date)=? && year(date)=? "; 

PreparedStatement stmt=DBConnectionDATABASE.prepareStatement(sql); 

try { 
    stmt.setString(1, get.Code()); 
    stmt.setString(2, get.Product()); 
    stmt.setInt(3, get.month()); 
    stmt.setInt(4, get.Year()); 

我怎樣才能找到上個月的最後一天數據。在sql中查找上個月的最後一天數據

+0

要設置上個月最後一天的參數,對嗎? –

+0

是的,我需要從sql – user1699623

+0

找到上個月的最後一天數據您是指上個月的確切最後一天,還是上個月的最後一天? – Adrian

回答

0

使用此查詢

select max(date) from sheet where date between ? and ? 

這將返回日期範圍

之間的最大日期,那麼

select * from sheet where date=(select max(date) from sheet where date between ? and ?); 

我清楚地知道,它不是不道德的使用聚合函數沒有group by但在這種情況下工作。

1
  1. 比較日期與少:where ... date<?
  2. 將該參數設置爲下個月開始的時候,你可以從年份和月份你拿到計算,見Calendar
  3. 訂單查詢按日期倒序:where ... order by date desc
  4. 如果你真的想只比限制查詢中的最後一項:where ... order by ... limit 1

整個查詢看起來是這樣的:

select amount, Temperature, Density from sheet where Code=? and product=? and date < ? order by date desc limit 1 
+0

所以我應該怎麼把這裏stmt.setDate(3,?????? ?????); – user1699623

+1

@Adrian嚴格來說,你應該檢查日期是否在上個月的開始之後 - 那個月可能根本沒有任何記錄。 – Alnitak

+0

@ user1699623下個月的第一秒,例如,如果你想要在7月1日的第一秒之內設置7月份。 – Adrian

0

爲了得到前一個月的最後一天

SELECT DATE_SUB(CURDATE() , INTERVAL DAYOFMONTH(CURDATE()) 
DAY) AS 'last_date' 
FROM dual 

然後LAST_DATE作爲查詢字符串日期參數

字符串SQL = 「選擇金額,\ n」 + 「溫度,\ n 「+ 」來自圖紙\ n「+ 」的密度\ n「+ 」其中Code =?和產品=?和日期=? 「

0

年整型= 2012; 月整型= 1; 日整型= 0; cal.set(年,月,日);
日期日期= cal.getTime();

這個日期設爲您的查詢 這將給2012年1月31日

如果你給個月= 2,它會給2012年2月29日等

+0

我通過cal.set(年,月,日)得到錯誤; – user1699623

+0

這將不起作用,因爲您仍然必須匹配數據庫中日期的小時,分​​鍾,秒......以及您提供的比較日期。 – Adrian

+1

使用此代碼012 =「select amount,\ n」+「Temperature,\ n」 =?和月份(日期)=?&年(日期)=?「 並設置參數 –

1

字符串SQL = 「選擇量,\ n」 + 「溫度,\ n」 + 「密度\ n」 + 「從片\ n」 +「,其中代碼=?和產物=?和日子(日期)= ?和月份(日期)=?& &年份(日期)=?「並設置參數

+0

感謝它是有用的,但我怎麼能找到上個月與數據的最後一天 – user1699623

+0

日曆cal = Calendar.getInstance(); \t \t \t int year = 2012; \t \t \t int month = 1; \t \t \t int day = 0; \t \t \t cal.set(year,month,day); \t \t \t day = cal.get(Calendar.DATE); 一天將是31 –

相關問題