--交叉表,根據優先順序取資料,日期處理
create table tb(qid int,rid nvarchar(4),tagname nvarchar(10),starttime smalldatetime,endtime smalldatetime,startweekday int,endweekday int,startdate smalldatetime,enddate smalldatetime,d int)
insert tb select 1,'a1','未訂','08:00','09:00',1 ,5 ,null ,null ,1
union all select 1,'a1','未訂','09:00','10:00',1 ,5 ,null ,null ,1
union all select 1,'a1','未訂','10:00','11:00',1 ,5 ,null ,null ,1
union all select 1,'a1','裝修','08:00','09:00',null,null,'2005-1-18','2005-1-19',2
--union all select 1,'a1','裝修','09:00','10:00',null,null,'2005-1-18','2005-1-19',2
union all select 1,'a1','裝修','10:00','11:00',null,null,'2005-1-18','2005-1-19',2
union all select 1,'a2','未訂','08:00','09:00',1 ,5 ,null ,null ,1
union all select 1,'a2','未訂','09:00','10:00',1 ,5 ,null ,null ,1
union all select 1,'a2','未訂','10:00','11:00',1 ,5 ,null ,null ,1
--union all select 1,'a2','裝修','08:00','09:00',null,null,'2005-1-18','2005-1-19',2
union all select 1,'a2','裝修','09:00','10:00',null,null,'2005-1-18','2005-1-19',2
--union all select 1,'a2','裝修','10:00','11:00',null,null,'2005-1-18','2005-1-19',2
go/*--樓主這個問題要考慮幾個方面
1. 取星期時,set datefirst 的影響
2. 優先順序問題
3. qid,rid 應該是未知的(動態變化的)
--*/
--實現的儲存過程如下
create proc p_qry
@date smalldatetime --要查詢的日期
asset nocount on
declare @week int,@s nvarchar(4000)
--格式化日期和得到星期
select @date=convert(char(10),@date,120)
,@week=(@@datefirst+datepart(weekday,@date)-1)%7
,@s=''
select id=identity(int),* into #t
from(
select top 100 percent
qid,rid,tagname,
starttime=convert(char(5),starttime,108),
endtime=convert(char(5),endtime,108)
from tb
where (@week between startweekday and endweekday)
or(@date between startdate and enddate)
order by qid,rid,starttime,d desc)a
select @s=@s+n',['+rtrim(rid)
+n']=max(case when qid='+rtrim(qid)
+n' and rid=n'''+rtrim(rid)
+n''' then tagname else n'''' end)'
from #t group by qid,rid
exec('
select starttime,endtime'+@s+'
from #t a
where not exists(
select * from #t
where qid=a.qid and rid=a.rid
and starttime=a.starttime
and endtime=a.endtime
and idgroup by starttime,endtime')
go--呼叫
exec p_qry '2005-1-17'
exec p_qry '2005-1-18'
go--刪除測試
drop table tb
drop proc p_qry
/*--測試結果
starttime endtime a1 a2
--------- ------- ---------- ----------
08:00 09:00 未訂 未訂
09:00 10:00 未訂 未訂
10:00 11:00 未訂 未訂
starttime endtime a1 a2
--------- ------- ---------- ----------
08:00 09:00 裝修 未訂
09:00 10:00 未訂 裝修
10:00 11:00 裝修 未訂
--*/
交叉表查詢統計
create table t class varchar 2 calldate datetime,callcount int insert into t select 1 2005 8 8 40 union all select 1 2005 8 7 6 union all select 2 200...
SQL動態交叉表
動態交叉表就是列表可以根據表中資料的情況動態建立列。動態查詢不能使用 select 語句實現,它可以利用儲存過程實現。思路是 首先檢索列頭資訊,形成乙個游標,然後遍歷游標,將上面靜態交叉表實現過程中使用 case 語句判斷的內容用游標裡的值替代,形成一條新的 sql查詢語句,然後執行並返回結果。下面...
SQL表交叉連線
mssql文件中也叫交叉聯接.好比 a表裡面的a,b,c 查詢符合a x 條件的.b表裡面 d,e,f 查詢符合 d 1 語句 select a.a,a.b,a.c,b.d,b.e b.f from a,b where a.a x b.d 1 這個是錯的.錯在 怎麼改?把 where裡面的,改為an...