我想知道历史上几个月中没有多少人,因为我有一个historicTable
,其中包含2012年至2018年的数据,每一行都包含多少时间员工没有空缺(职位空缺,疾病等),这就是一个例子:
idUser startDate endDate daysUn reason nameEmp
--------------------------------------------------------
123 25/01/2018 09/02/2018 12 Sickness John Doe
这是我每一行所需要的
idUser startDate endDate daysUn reason nameEmp
--------------------------------------------------------
123 25/01/2018 31/01/2018 5 Sickness John Doe
123 01/01/2018 09/02/2018 7 Sickness John Doe
我知道这里已经被问过百次了,但是我在整个表中都遇到了麻烦,因为我尝试了不同的答案,所有处理工作都针对给定的startdate和enddate列,而我需要的是将所有数据附加到此表并按原样保存,以便分析师能够研究特定案例和特定员工。这就是我当前的代码所得到的:
original_INI original_FIN new_INI new_FIN
----------------------- ----------------------- ----------------------- -----------------------
2017-10-15 00:00:00.000 2018-01-06 00:00:00.000 2017-10-15 00:00:00.000 2017-10-31 00:00:00.000
2017-10-15 00:00:00.000 2018-01-06 00:00:00.000 2017-11-01 00:00:00.000 2017-11-30 00:00:00.000
2017-10-15 00:00:00.000 2018-01-06 00:00:00.000 2017-12-01 00:00:00.000 2017-12-31 00:00:00.000
2017-10-15 00:00:00.000 2018-01-06 00:00:00.000 2018-01-01 00:00:00.000 2018-01-06 00:00:00.000
这是代码,原始日期还可以,因为我可以更全局地对数据进行排序,但是它可以打印并保存其余数据,因此更具可读性:
;WITH n(n) AS
(
SELECT ROW_NUMBER() OVER (ORDER BY [object_id])-1 FROM sys.all_columns
),
d(n,f,t,md,bp,ep) AS
(
SELECT n.n, d.INI, d.FIN,
DATEDIFF(MONTH, d.INI, d.FIN),
DATEADD(MONTH, n.n, DATEADD(DAY, 1-DAY(INI), INI)),
DATEADD(DAY, -1, DATEADD(MONTH, 1, DATEADD(MONTH, n.n,
DATEADD(DAY, 1-DAY(INI), INI))))
FROM n INNER JOIN archivoFuente AS d
ON d.FIN >= DATEADD(MONTH, n.n-1, d.INI)
)
SELECT original_INI = f, original_FIN = t,
new_INI = CASE n WHEN 0 THEN f ELSE bp END,
new_FIN = CASE n WHEN md THEN t ELSE ep END
FROM d WHERE md >= n
ORDER BY original_INI, new_INI;
感谢您对查询的任何帮助。
答案 0 :(得分:2)
实际上这很容易,我使用了相同的代码来满足要求,您需要调用每个select
语句中的每一列,因此在拆分行时它就存在,请检查此代码:
;WITH n(n) AS
(
SELECT ROW_NUMBER() OVER (ORDER BY [object_id])-1 FROM sys.all_columns
),
d(n,f,t,md,bp,ep,
--CALL YOUR COLUMNS HERE EG: name, id, bla, ble
) AS
(
SELECT n.n,d.INI, d.FIN,
DATEDIFF(MONTH, d.INI, d.FIN),
DATEADD(MONTH, n.n, DATEADD(DAY, 1-DAY(INI), INI)),
DATEADD(DAY, -1, DATEADD(MONTH, 1, DATEADD(MONTH, n.n,
DATEADD(DAY, 1-DAY(INI), INI)))),
--CALL YOUR COLUMNS HERE AGAIN, PAY ATTENTION TO NAMES AND COMMAS
d.id_hr,d.Tipo,d.ID_tip,d.Nom_inc,d.RUT,d.Nombre,d.ID_emp,d.Nom_pos,d.Dias_durac,d.Num_lic,d.ID_usu_ap,d.ult_act
FROM n INNER JOIN archivoFuente AS d
ON d.FIN >= DATEADD(MONTH, n.n-1, d.INI)
)
SELECT --PUT ONCE AGAIN YOUR COLUMNS HERE, THIS WILL WORK FOR THE DISPLAYED RESULT
original_INI = f, original_FIN = t,
new_INI = CASE n WHEN 0 THEN f ELSE bp END,
new_FIN = CASE n WHEN md THEN t ELSE ep END
FROM d
WHERE md >= n
ORDER BY original_INI, new_INI;
现在,要保存表,我建议对新表使用INSERT
语句,您将如何做,我不知道,我和您在同一地点。希望有人检查这个问题。