SQL 中的單列資料到多列資料的轉換,以及轉換後的分組統計

來源:互聯網
上載者:User

手上有一個供求資訊網站,客戶要要求對其中的企業會員每月的供求資訊發布量進行統計
要求以如下形式列印:
2006-10-1 到 2006-10-31
使用者    供應數   求購數   合計   詳細
張山    10           20          30       >>
李四     50           3            53      >>

。。。。。

現有的供求資訊表(Info)表結構如下
User             Info_ID       dateAndTime  type
WDFrog       1                   ...                       買
WDFrog       2                                             賣
WDFrog       3                                             賣
lxj                   4                                            賣
lxj                   5                                            買

則將type列拆分成  sell , buy 2列的代碼如下:
   Select [Id], [user],
              case [type]
                   When '買' Then 1
               Else 0 
               End As buy,
               Case [type]
                    When '賣' Then 1
               Else 0
               End as sell      
    From info

統計求和的代碼如下:

   Select [Id], [user],
           SUM(case [type]
               When '買' Then 1
               Else 0 
        End ) As buy,
           SUM(Case [type]
               When '賣' Then 1
               Else 0
               End ) as sell,
           count(info_id) as total
           
    From vi_AgentInfo

    Group by [Id],[user] Order by total DESC

最後還可以這樣寫,列印效果怎樣?大家不妨自己去試試

Select [Id],[user],
case [type]
      When '買' Then '買'
      Else '賣'
      End As BAndS,
      count([Id]) as total

From vi_AgentInfo
Group by
 case [type]
      When '買' Then '買'
      Else '賣'
      End
      ,[Id],[user]

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.