萬盛學電腦網

 萬盛學電腦網 >> 數據庫 >> mysql教程 >> sql group by語法與實例

sql group by語法與實例

   sql group by語法與實例

  group by 語句

  group by 語句用於結合合計函數,根據一個或多個列對結果集進行分組。

  sql group by 語法

  select column_name, aggregate_function(column_name)

  from table_name

  where column_name operator value

  group by column_name

  來看一個group by實例

  比如表裡內容是這樣

  gameid best top spam

  111 1 1 1

  121 1 1 0

  123 0 1 1

  111 1 0 1

  我現在要取出best top spam 的數量 結果應該是

  gameid best top spam

  111 2 1 2

  121 1 1 0

  123 0 1 1

  select gameid, sum(best) as bestcnt, sum(top) as tocnt, sum(spam) as spamcnt

  from table

  group by gameid

  在php教程 中使用方法

  $sql = "select gameid,sum(best) as best,sum(top) as top,sum(spam) as spam, from tablename group by gameid order by gameid asc";

  再來看個簡單一點的實例

  數據庫教程表table

  日期 勝負

  2009-12-9 勝

  2009-12-9 勝

  2009-12-9 負

  2009-12-9 負

  2009-12-10 負

  2009-12-10 勝

  2009-12-10 負

  查詢結果

  日期 勝 負

  2009-12-9 2 2

  2009-12-10 1 2

  select 日期,

  sum(decode(勝負,'勝',1,0)),

  sum(decode(勝負,'負',1,0))

  from 數據庫表

  group by 日期

copyright © 萬盛學電腦網 all rights reserved