使用動態SQL語句實現簡單的行列轉置(動態產生列)

bfc99發表於2014-03-31
以下轉自:http://hi.baidu.com/leowong/item/329bd8f7e2080e0b84d27880 作者:七月初七

使用動態SQL語句實現簡單的行列轉置(動態產生列)

原始資料如下圖所示:(商品的銷售明細)
date=業務日期;Item=商品名稱;saleqty=銷售數量;

-- 建立測試資料(表)
create table test (Date varchar(10), item char(10),saleqty int)
insert test values('2010-01-01','AAA',8)
insert test values('2010-01-02','AAA',4)
insert test values('2010-01-03','AAA',5)
insert test values('2010-01-01','BBB',1)
insert test values('2010-01-02','CCC',2)
insert test values('2010-01-03','DDD',6)

需要實現的報表樣式:每一行既每一天,顯示所有商品(列)該天的銷售數量;



實現的方法和思路如下:

-- 實現結果的靜態SQL語句寫法
-- 整理報表需要的格式
select date,
case item when 'AAA' then saleqty when null then 0 end as AAA,
case item when 'BBB' then saleqty when null then 0 end as BBB,
case item when 'CCC' then saleqty when null then 0 end as CCC,
case item when 'DDD' then saleqty when null then 0 end as DDD
from test




-- 按日期彙總行
select date,
sum(case item when 'AAA' then saleqty when null then 0 end) as AAA,
sum(case item when 'BBB' then saleqty when null then 0 end) as BBB,
sum(case item when 'CCC' then saleqty when null then 0 end) as CCC,
sum(case item when 'DDD' then saleqty when null then 0 end) as DDD
from test 
group by date


-- 處理資料:將空值的欄位填入數字0;
select date,
isnull (sum(case item when 'AAA' then saleqty end),0) as AAA,
isnull (sum(case item when 'BBB' then saleqty end),0) as BBB,
isnull (sum(case item when 'CCC' then saleqty end),0) as CCC,
isnull (sum(case item when 'DDD' then saleqty end),0) as DDD
from test 
group by date


靜態SQL語句編寫完成!

-- 需要動態實現的SQL部分
isnull (sum(case item when 'AAA' then saleqty end),0) as AAA,
isnull (sum(case item when 'BBB' then saleqty end),0) as BBB,
isnull (sum(case item when 'CCC' then saleqty end),0) as CCC,
isnull (sum(case item when 'DDD' then saleqty end),0) as DDD

-- 動態語句的實現
select 'isnull (sum(case item when '''+item+''' then saleqty end),0) as ['+item+']' 
from (select distinct item from test) as a
-- 這一步很關鍵:利用結果集給變數賦值;

-- 完成!
declare @sql varchar(8000)
set @sql = 'select Date'
select @sql = @sql + ',isnull (sum(case item when '''+item+''' then saleqty end),0) as ['+item+']' 
from (select distinct item from test) as a
select @sql = @sql+' from test group by date'
exec(@sql)

-- 刪除測試資料(表)
drop table test

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/22207394/viewspace-1133152/,如需轉載,請註明出處,否則將追究法律責任。

相關文章