sql group by文法與執行個體

來源:互聯網
上載者:User

   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 日期

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.