生成交叉表的SQL基本語句

2021-07-25 06:31:58 字數 873 閱讀 8846

在企業資訊化管理中,經常需要提供交叉表形式的資料給管理層。

如以月份為縱軸,客戶銷售金額為橫軸。

以下以sql自帶資料庫舉例列出sql語句:

--定義長度為8000的字串變數@msql

declare @msql varchar(8000)

--橫軸字段

select @msql=' select month(orderdate) as 月份'

--從訂單表中取出一定條件(where orderdate between '1996-07-01' and '1996-07-31')範圍內

--所有客戶id並連線至@msql

select @msql=@msql+',sum(case when customerid='''+rtrim(customerid)+''' then freight else 0 end) as ['+rtrim(customerid)+']'

from (select distinct customerid from orders where orderdate between '1996-07-01' and '1996-07-31')a

--上面語句是生成交叉表橫軸的關鍵

--在一定條件範圍取數並按橫軸字段彙總

select @msql=@msql+' from orders where orderdate between ''1996-07-01'' and ''1996-07-31'' group by  month(orderdate)'  

--執行

exec (@msql)

總結:1.生成的字串長度不能超過8000,否則出錯

2.以上是最基本的生成交叉表的sql語句,在實際應用中,可加入多重條件、左右關聯等等從而得到更複雜的結果

列自動生成(交叉表 crosstab)

if not object id today is null drop table today go create table today id int identity 1,1 primary key,inmoney int,date smalldatetime,name varchar 20 i...

生成交叉表的簡單通用儲存過程

if exists select from dbo.sysobjects where id object id n dbo p qry and objectproperty id,n isprocedure 1 drop procedure dbo p qry go 生成交叉表的簡單通用儲存過程 根...

生成交叉表的簡單通用儲存過程

if exists select from dbo.sysobjects where id object id n dbo p qry and objectproperty id,n isprocedure 1 drop procedure dbo p qry go 生成交叉表的簡單通用儲存過程 根...