動態交叉表的實現

2021-05-10 08:37:58 字數 1169 閱讀 8145

declare @sql varchar(8000)

set @sql = 'select makedate,'

select @sql = @sql + 'sum(case status when '''+status+'''

then status else 0 end) as '''+status+''','

from (select distinct status from e3_m_process) as a

select @sql = left(@sql,len(@sql)-1) + ' from e3_m_process group by makedate'

print @sql

標準語法。

declare @sql varchar(8000)

set @sql = 'select name,'

select @sql = @sql + 'sum(case subject when '+''''+subject+''''+'

then source else 0 end) as '+''''+subject+''''+','

from (select distinct subject from test) as a

select @sql = left(@sql,len(@sql)-1) + ' from test group by name'

exec(@sql)

標準執行。

內部子查詢裡面查詢的必須是數值型的,因為外層用的是sum

declare @sql varchar(8000)

set @sql = 'select style_id,'

select @sql = @sql + 'sum(case status when '''+status+'''

then status else 0 end) as '''+status+''','

from (select distinct status from m2c_mrpd_style where not status is null) as a

select @sql = left(@sql,len(@sql)-1) + ' from m2c_mrpd_style group by style_id'

print @sql

語句的進一步完善。假如為空,會出現沒語句輸出的情況。

動態交叉表的實現

create procedure corsstab strtabname as varchar 50 employees 此處放表名 strcol as varchar 50 city 表頭分組依據字段 strgroup as varchar 50 titleofcourtesy 分組字段 strn...

SQL實現動態交叉表 用游標實現

set quoted identifier on goset ansi nulls on goalter procedure crosstable strtablename as varchar 50 查詢表 strcol as varchar 50 strgroup as varchar 50 分...

SQL動態交叉表

動態交叉表就是列表可以根據表中資料的情況動態建立列。動態查詢不能使用 select 語句實現,它可以利用儲存過程實現。思路是 首先檢索列頭資訊,形成乙個游標,然後遍歷游標,將上面靜態交叉表實現過程中使用 case 語句判斷的內容用游標裡的值替代,形成一條新的 sql查詢語句,然後執行並返回結果。下面...