日期:2014-05-17 浏览次数:20365 次
----------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2013-05-21 21:05:36
-- Version:
-- Microsoft SQL Server 2008 R2 (SP1) - 10.50.2500.0 (Intel X86)
-- Jun 17 2011 00:57:23
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition on Windows NT 6.1 <X86> (Build 7601: Service Pack 1)
--
----------------------------
--> 测试数据:[A]
if object_id('[A]') is not null drop table [A]
go
create table [A]([日期] datetime,[数据] int)
insert [A]
select '2013-05-21',100 union all
select '2013-04-21',50 union all
select '2013-01-01',123 union all
select '2013-02-01',456
--------------开始查询--------------------------
SELECT a.日期,a.数据,b.数据
FROM
(SELECT 日期,数据 ,DATEADD(MONTH,-1,日期)上月同期
FROM A)A LEFT JOIN (SELECT 日期,数据
FROM A)B ON a.上月同期=b.日期
----------------结果----------------------------
/*
日期 数据 数据
----------------------- ----------- -----------
2013-05-21 00:00:00.000 100 50
2013-04-21 00:00:00.000 50 NULL
2013-01-01 00:00:00.000 123 NULL
2013-02-01 00:00:00.000 456 123
*/