27,579
社区成员
发帖
与我相关
我的任务
分享
;with Flats as(),FT as()
select * from FT
用到兩個CTE,有哪個高手可以有用到兩個CTE的簡單例子啊?一般什麽情況下要用到兩個CTE。
----------------------------------------------------------------
-- Author :fredrickhu(我是小F,向高手学习)
-- Date :2009-11-09 14:14:36
-- Version:
-- Microsoft SQL Server 2005 - 9.00.4035.00 (Intel X86)
-- Nov 24 2008 13:01:59
-- Copyright (c) 1988-2005 Microsoft Corporation
-- Developer Edition on Windows NT 5.2 (Build 3790: Service Pack 1)
--
----------------------------------------------------------------
--> 测试数据:[tb]
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([number] int,[date] datetime)
insert [tb]
select 8,'2009/1/11 2:00' union all
select 7,'2009/1/11 5:00' union all
select 6,'2009/1/11 12:00' union all
select 5,'2009/1/11 18:00' union all
select 4,'2009/1/12 4:00' union all
select 3,'2009/1/12 10:00' union all
select 2,'2009/1/12 12:00' union all
select 1,'2009/1/12 17:00'
--------------开始查询--------------------------
;with f1 as
(
select
*
from
[tb] t
where
date=(select min(date) from tb where convert(varchar(10),date,120)=convert(varchar(10),t.date,120))
),
f2 as
(
select
*
from
[tb] t
where
date=(select max(date) from tb where convert(varchar(10),date,120)=convert(varchar(10),t.date,120))
)
select f1.number-f2.number from f1,f2 where convert(varchar(10),f1.date,120)=convert(varchar(10),f2.date,120)
----------------结果----------------------------
/*
-----------
3
3
(2 行受影响)
*/