我有一个表,用于存储EmployeeId、TourMonth、StartMonth、EndMonth
。
TourMonth
代表月份,1
代表一月,2
代表二月等。
我想从此表中找到给定的 startdate
和 enddate
之间缺少的月份。下面给出了员工 3071 从 1 月到 12 月的示例,其中缺少 2 月、4 月、7 月、9 月。我怎样才能从表中得到结果?
EmployeeId TourMonth StartMonth EndMonth
--------- --------- --------- --------
3071 1 2015-01-13 00:00:00.000 2015-01-14 00:00:00.000
3071 3 2015-03-15 00:00:00.000 2015-04-15 00:00:00.000
3071 5 2015-05-15 00:00:00.000 2015-06-15 00:00:00.000
3071 6 2015-06-15 00:00:00.000 2015-07-15 00:00:00.000
3071 8 2015-08-15 00:00:00.000 2015-09-15 00:00:00.000
3071 10 2015-10-15 00:00:00.000 2015-11-15 00:00:00.000
我想要的输出:
如果我传入 startdate = 2015-01-01
和 enddate = 2015-11-01
和 EmployeeId = 3071
,那么我应该得到:
EmployeeId MissingMonth
----------- ------------
3071 February
3071 April
3071 July
3071 September
最佳答案
为了使代码更直接,请创建包含月份名称的表:
IF EXISTS (SELECT * FROM sys.all_objects WHERE object_id = OBJECT_ID('[dbo].[tbl_Months]') AND type IN ('U'))
DROP TABLE [dbo].[tbl_Months]
GO
CREATE TABLE [dbo].[tbl_Months] (
[id] int NULL,
[month] varchar(20) COLLATE Latin1_General_CI_AS NULL
)
ON [PRIMARY]
GO
-- ----------------------------
-- Records of tbl_Months
-- ----------------------------
BEGIN TRANSACTION
GO
INSERT INTO [dbo].[tbl_Months] VALUES ('1', 'January');
INSERT INTO [dbo].[tbl_Months] VALUES ('2', 'February');
INSERT INTO [dbo].[tbl_Months] VALUES ('3', 'March');
INSERT INTO [dbo].[tbl_Months] VALUES ('4', 'April');
INSERT INTO [dbo].[tbl_Months] VALUES ('5', 'May');
INSERT INTO [dbo].[tbl_Months] VALUES ('6', 'June');
INSERT INTO [dbo].[tbl_Months] VALUES ('7', 'July');
INSERT INTO [dbo].[tbl_Months] VALUES ('8', 'August');
INSERT INTO [dbo].[tbl_Months] VALUES ('9', 'September');
INSERT INTO [dbo].[tbl_Months] VALUES ('10', 'October');
INSERT INTO [dbo].[tbl_Months] VALUES ('11', 'November');
INSERT INTO [dbo].[tbl_Months] VALUES ('12', 'December');
GO
COMMIT
然后简单选择:
SELECT [id], [month] from tbl_Months
WHERE NOT EXISTS (SELECT TourMonth FROM table_name WHERE "some conditions")
我不会解释 WHERE 某些条件,因为它可能有很多变体
- 您可以按日期进行精确比较 - 例如 StartMonth = '2015-10-15' 和 start_date = '2015-10-16' 可以包含本月,但不能包含逻辑。
- 或根据您的逻辑按日期的一部分(月份)
关于sql - 从表中获取缺失的月份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33717597/