日期:2014-05-17  浏览次数:20357 次

SQL SERVER 查询问题



如图。。。黄色区域为原表,白色区域是希望得到的结果,请问SQL语句要怎么写

http://zhidao.baidu.com/question/528643577?quesup2&oldq=1

------解决方案--------------------
select a.time,a.F1,b.F1 as F2  from (select * from table1 where F1<='d') a 
left join   (select * from table1 where F1>'d')  b on a.time=b.time

------解决方案--------------------
----------------------------
-- Author  :磊仔
-- Date    :2013-03-01 22:33:07
-- Version:  
--      Microsoft SQL Server 2008 R2 (SP2) - 10.50.4000.0 (Intel X86)   
-- Jun 28 2012 08:42:37   
-- Copyright (c) Microsoft Corporation  
-- Enterprise Edition on Windows NT 6.1 <X86> (Build 7600: )  
--
----------------------------
--> 测试数据:#TA
if object_id('tempdb.dbo.#TA') is not null drop table #TA
go 
create table #TA([Time] int,[F1] varchar(1))
insert #TA
select 1,'a' union all
select 2,'b' union all
select 3,'c' union all
select 4,'d' union all
select 1,'e' union all
select 2,'f' union all
select 3,'g'
--------------开始查询--------------------------

;with cet as
(select *,ROW_NUMBER()over(partition by Time order by F1)rn 
from #TA
)
select distinct a.Time,b.F1,c.F1 as F2 
from #TA a 
left join cet b on a.Time = b.Time and b.rn = 1
left join cet c on a.Time = c.Time and c.rn = 2
order by a.Time


----------------结果----------------------------
/*   
Time        F1   F2
----------- ---- ----
1           a    e
2           b    f
3           c    g
4           d    NULL

(4 行受影响)
*/