SQL中的交叉表

來源:互聯網
上載者:User

有時候需要將結果旋轉以便在水平方向顯示列,水平方向顯示行,即所謂的交叉表(PrvotTable)。在SQL顯示它也比較的簡單:
1:結果確定的交叉表:
       Year      Quarter      Amount(表Prvot)
       ----          -------           ------
       1990         1               1.1                    
       1990         2               1.2          顯示成:   Year          Q1            Q2                 Q3                Q4
       1990         3               1.3                            -----           ---             ----                 ---                 ---
       1990         4               1.4                          1990            1.1            1.2               1.3               1.4   
      因為Quarter是固定的,姑且稱其為結果確定的交叉表吧。實現的方法如下:
      SELECT Year,
            SUM(CASE Quarter WHEN 1 THEN Amount ELSE 0 END) AS Q1,
            SUM(CASE Quarter WHEN 2 THEN Amount ELSE 0 END) AS Q2,
            SUM(CASE Quarter WHEN 3 THEN Amount ELSE 0 END) AS Q3,
            SUM(CASE Quarter WHEN 4 THEN Amount ELSE 0 END) AS Q4
       FROM Prvot
       GROUP BY Year(具體參考SQL的協助,搜尋交叉資料表即可)
2:結果不確定的交叉表:
     假如Quarter是動態變動的,那麼就不能簡單的使用上述的case...when了,可以構造動態SQL語句,來實現上述的SUM語  句。
     declare @goodscode varchar(20)
     declare @goodsname varchar(40)
     declare @str varchar(2000)

     set @str = ''

     declare goods_cur cursor for
          select goodscode,goodsname
          from pub_goods
         order by goodscode

    open goods_cur
    fetch next from goods_cur into @goodscode,@goodsname
    while @@fetch_status = 0
      begin
         set @str = @str + 'sum(case goodscode when ''' + @goodscode + ''' then targetqty else 0 end) as ''' + @goodsname + ''','
         fetch next from goods_cur into @goodscode,@goodsname
      end
   close goods_cur
   deallocate goods_cur
   set @str = substring(@str,1,len(@str)-1)
   exec('select districtcode,' + @str + ' from ( select distinct districtcode,goodscode,targetqty  from report_hospital_use   where  
             districtcode is not null   ) as t group by districtcode')

3:現在的問題是,能不能不使用遊標來實現上述的SUM語句的構造過程。

聯繫我們

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