自動增加長列的使用加行列轉換

2022-07-19 20:27:19 字數 3951 閱讀 3379

客戶需求這樣的結果,還要求可以按要求時間(t1)查詢:

建立的資料表如下(table_1):

資料如下:

怎樣才能把 table_1 這樣的資料變成 t1這樣的如下sql

步驟如下:

1. 把當天不需要的資料去掉:如下:

2. 時間序列與房間的列表,這樣規定的時間內所有的資料都為0

select *,0 as cb from(

select distinct rooms from table_1) as a1,(

select stuff(stuff(convert(char(8),dateadd(day,id-1,@begindays),112),5,0,n'-'),8,0,n'-')+n'' as times from  @b) as a2

3. 再和時間序列並在一起(這樣每一天的資料都有了)

4.進行行列變換

declare @begindays datetime

set @begindays = '2013-07-01'

declare @enddays datetime

set @enddays  = '2013-08-01'

declare @days int;

set @days = datediff(day,@begindays,@enddays);

declare @rooms varchar(50);

set @rooms = 'a4-09-01';

declare @sql nvarchar(max);

set @sql =  'declare @b table(id int identity,a int default 0); ';

set @sql = @sql +'insert @b select top 100 0 from syscolumns s ;';

set @sql = @sql+ ' declare @begindays datetime;';

set @sql = @sql+ ' set @begindays = '''+stuff(stuff(convert(char(8),@begindays,112),5,0,n'-'),8,0,n'-')+'''';

set @sql = @sql+ ' declare @enddays datetime;';

set @sql = @sql+ ' set @enddays = '''+stuff(stuff(convert(char(8),@enddays,112),5,0,n'-'),8,0,n'-')+'''';

set @sql = @sql+ ' declare @days  int;';

set @sql = @sql+ ' set @days = datediff(day,@begindays,@enddays)';

set @sql = @sql+ ' declare @rooms varchar(50);';

set @sql = @sql+ ' set @rooms = '''+@rooms+'''';

set @sql=  @sql +' select rooms ';

select  @sql = @sql +' ,max(case when times = stuff(stuff(convert(char(8),dateadd(day,'''+cast (number as varchar(3))+'''-0,@begindays),112),5,0,''-''),8,0,''-'') then cb else 0 end) as   '''+stuff(stuff(convert(char(8),dateadd(day, number ,@begindays),112),5,0,'-'),8,0,'-') +''''

from  master..spt_values where [type] = 'p' and number

set @sql = @sql + 'from (

select rooms,times,max(cb) as cb from(

select rooms,times,0 as cb from(

select distinct rooms from table_1) as a1,(

select stuff(stuff(convert(char(8),dateadd(day,id-1,@begindays),112),5,0,''-''),8,0,''-'') as times from  @b) as a2

union

select rooms,times,max(cb) as cb from(

select rooms,stuff(stuff(convert(char(8),max(times),112),5,0,''-''),8,0,''-'') as times,max(cb) as cb from table_1 where times > @begindays and times < @enddays   group by rooms,times

) as t5 group by rooms,times

) as t6 group by rooms,times

) as tt1  group by rooms'

print (@sql)

print (len(@sql))

exec(@sql)

這樣就行成了最後的結查。

使用jqgrid增加行的時候如何拼接控制項的name

在使用jqgrid編輯 的時候,會出現我們新增行無法將控制項的name拼接為list.name的形式,所以我們需要在提交 的時候將name更換掉。具體是的實現邏輯為 param listname 拼接的list物件名 list param fieldnames 要拼接的name名 aa functi...

MySQL中自動增長列ID的使用

mysql中自動增長列id的使用 mysql 中可以通過auto increment 屬性為新的行產生唯一的標識,如 create table animals id int not null auto increment,name varchar 10 insert into animals nam...

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

原始資料如下圖所示 商品的銷售明細 date 業務日期 item 商品名稱 saleqty 銷售數量 建立測試資料 表 create table test date varchar 10 item char 10 saleqty int insert test values 2010 01 01 a...