2011-04-05 64 views
0

我如何計算一個值在使用jdbc的表中出現的次數?我有200個可能的值和4列記錄在表中。在數據庫中計數值

+0

你想要計算每個值,還是隻有一個? – 2011-04-05 08:40:24

回答

6

可以由

Select count(*) from table where item = 'value'; 

如果你想指望所有200個值,那麼你可以嘗試:

select item,count(*) from table group by item; 

演示代碼: -

try { 
     java.sql.Statement s = conn.createStatement(); 
     java.sql.ResultSet r = s.executeQuery("select item,count(*) from table group by item;"); 
     while (r.next()) { 
      System.out.println(r.getString(1) + " " 
        + r.getString(2)); 
     } 
    } catch (Exception e) { 
     System.out.println(e); 
     System.exit(0); 
    } 
+0

非常感謝,但你能向我解釋如何在java程序中編寫這個語句。我嘗試把我的程序,但我得到nullpointer exception.tq – user692495 2011-04-06 05:42:53

+0

@ user692495:看到我的演示代碼。它可能會幫助你。 – 2011-04-06 05:50:27

+0

yeaaahh ...這是工作,非常感謝你:-) – user692495 2011-04-06 06:04:15