# 各位大俠﹐請幫我看一看﹐下面這個查詢怎么寫才能提高效率

szdufeng 2006-03-11 11:36:39
select work_id,sdate,
work_from1=(select min(stime) from #er where a.work_id=work_id and case when right(state,1)='A' then convert(varchar(10),DATEADD(day,1,a.sdate),120) else a.sdate end=sdate and left(state,1)=1 and substring(state,2,1)=1),
work_to1=(select max(stime) from #er where a.work_id=work_id and case when right(state,1)='A' then convert(varchar(10),DATEADD(day,1,a.sdate),120) else a.sdate end=sdate and left(state,1)=2 and substring(state,2,1)=0),
work_from2=(select min(stime) from #er where a.work_id=work_id and case when right(state,1)='A' then convert(varchar(10),DATEADD(day,1,a.sdate),120) else a.sdate end=sdate and left(state,1)=3 and substring(state,2,1)=1),
work_to2=(select max(stime) from #er where a.work_id=work_id and case when right(state,1)='A' then convert(varchar(10),DATEADD(day,1,a.sdate),120) else a.sdate end=sdate and left(state,1)=4 and substring(state,2,1)=0),
work_from3=(select min(stime) from #er where a.work_id=work_id and case when right(state,1)='A' then convert(varchar(10),DATEADD(day,1,a.sdate),120) else a.sdate end=sdate and left(state,1)=5 and substring(state,2,1)=1),
work_to3=(select max(stime) from #er where a.work_id=work_id and case when right(state,1)='A' then convert(varchar(10),DATEADD(day,1,a.sdate),120) else a.sdate end=sdate and left(state,1)=6 and substring(state,2,1)=0)

from #er a

group by work_id,sdate

#er表格式如下:
card_id sdate stime state
107073 2006-02-28 0800 60A
107073 2006-02-28 1950 11
107073 2006-02-28 2330 20
107073 2006-03-01 0020 31A
107073 2006-03-01 0800 60A
106376 2006-02-20 0753 11
106376 2006-02-20 1130 20

...全文
76 点赞 收藏 5

5 条回复

szdufeng 2006-03-11

care_id sdate work_from1 work_to1 work_from2 work_to2 work_from3 work_to3
100197 2006-02-20 1954 2331 0023 NULL NULL 0800
100197 2006-02-21 1952 2331 0023 NULL NULL 0800
100197 2006-02-22 1951 2331 0025 NULL NULL 0800
100197 2006-02-23 1952 2331 0026 NULL NULL 0800
100197 2006-02-24 1950 2330 0025 NULL NULL 0800
100197 2006-02-25 1951 2331 0025 NULL NULL 0802
100197 2006-02-26 NULL NULL NULL NULL NULL NULL
100197 2006-02-27 1955 2330 0026 NULL NULL 0800
100197 2006-02-28 1950 2331 0023 NULL NULL 0800
100197 2006-03-01 NULL NULL NULL NULL NULL NULL
100302 2006-02-21 0756 1202 1320 1730 1823 2133

szdufeng 2006-03-11
#er表每次運行時應該都 有20000條以上的記錄的

szdufeng 2006-03-11

szdufeng 2006-03-11

care_id sdate work_from1 work_to1 work_from2 work_to2 work_from3 work_to3
107073 2006-02-28 1950 2330 0020 0800 null null
106376 2006-02-20 0753 1130 null null null null

lsqkeke 2006-03-11
#er表格式如下:
card_id sdate stime state
107073 2006-02-28 0800 60A
107073 2006-02-28 1950 11
107073 2006-02-28 2330 20
107073 2006-03-01 0020 31A
107073 2006-03-01 0800 60A
106376 2006-02-20 0753 11
106376 2006-02-20 1130 20

2.1w+

MS-SQL Server 疑难问题

2006-03-11 11:36