日期:2014-05-18 浏览次数:20491 次
--> 测试数据:[入职表] IF OBJECT_ID('[入职表]') IS NOT NULL DROP TABLE [入职表] GO CREATE TABLE [入职表]([入职日期] DATETIME) INSERT [入职表] SELECT '2012-07-08' UNION ALL SELECT '2012-07-12' --------------开始查询-------------------------- --> 测试数据:[离职表] IF OBJECT_ID('[离职表]') IS NOT NULL DROP TABLE [离职表] GO CREATE TABLE [离职表]([离职日期] DATETIME) INSERT [离职表] SELECT '2012-07-06' UNION ALL SELECT '2012-06-01' --------------开始查询-------------------------- SELECT DISTINCT YEAR(ISNULL(a.[入职日期],b.[离职日期])) AS 年,MONTH(ISNULL(a.[入职日期],b.[离职日期])) AS 月, (select count(*) FROM [入职表] WHERE CONVERT(VARCHAR(7),[入职日期],120)=CONVERT(VARCHAR(7),a.[入职日期],120)) AS 入职人数 , (select count(*) FROM [离职表] WHERE CONVERT(VARCHAR(7),[离职日期],120)=CONVERT(VARCHAR(7),b.[离职日期],120)) AS 离职人数 FROM [入职表] AS a FULL JOIN [离职表] AS b ON CONVERT(VARCHAR(7),a.[入职日期],120)=CONVERT(VARCHAR(7),b.[离职日期],120) ----------------结果---------------------------- /* 年 月 入职人数 离职人数 ----------- ----------- ----------- ----------- 2012 6 0 1 2012 7 2 1 (2 行受影响) */
------解决方案--------------------
select datepart(year,t.[日期]) '年份',datepart(month,t.[日期]) '月份',t.[入职人数],t.[离职人数] from ( select (case when ([入职日期] IS NOT NULL AND [离职日期] IS NOT NULL) or ([入职日期] IS NOT NULL AND [离职日期] IS NULL) THEN [入职日期] case when [入职日期] IS NULL AND [离职日期] IS NOT NULL THEN [离职日期] END) '日期',ISNULL([入职人数],0) '入职人数',ISNULL([离职人数],0) '离职人数' from ( select convert(varchar(7),[入职日期],120) '入职日期',sum(convert(varchar(7),[入职日期],120)) '入职人数' from [入职表] GROUP BY convert(varchar(7),[入职日期],120) ) a full join ( select convert(varchar(7),[离职日期],120) '离职日期',sum(convert(varchar(7),[离职日期],120)) '离职人数' from [离职表] GROUP BY convert(varchar(7),[离职日期],120)) ) b on a.[入职日期]=b.[离职日期] ) t