我需要能够确定平均天数并检查项目。我试图计算一个项目记录的借用次数和每次出现的借用天数。 数据如下所示:
CREATE TABLE project (
transnum int,
transdate datetime,
transtype int,
itemrecord int,
collection int
);
INSERT INTO project (transnum,transdate,transtype,itemrecord,collection)
VALUES
(1, '2018-01-02 12:15:00.000', 6001, 3617581, 1),
(3, '2018-01-09 14:17:01.000', 6001, 3617581, 1),
(7, '2018-01-14 09:11:15.000', 6002, 3617581, 1),
(9, '2018-02-02 12:15:00.000', 6001, 3617581, 1),
(12, '2018-02-09 10:50:00.000', 6002, 3617581, 1),
(15, '2018-02-11 09:17:10.000', 6001, 3617581, 1),
(16, '2018-02-18 15:01:35.000', 6001, 3617581, 1),
(20, '2018-02-20 08:54:00.000', 6002, 3617581, 1),
(22, '2018-02-22 15:21:16.000', 6001, 3617581, 1),
(23, '2018-02-23 13:15:00.000', 6001, 3677214, 2),
(25, '2018-02-25 17:21:00.000', 6002, 3677214, 2);
物品记录被检出(6001),然后检入(6002),但在重新检入之前,物品也有可能被更新(也是6001)。
所以,例如,itemrecord 3617581被检查了5次(因为在报告的范围内没有最终检入(6002),因此2-22的结账没有计算)所以收集1的平均结账将是28 / 5或5天。
itemrecord Daysout Collection
3617581, 7 1
3617581, 5 1
3617581, 7 1
3617581, 7 1
3617581, 2 1
答案 0 :(得分:1)
您想要根据6002分割数据。然后采取最早的6001.这样做的方法是反向,条件,累积和:
select itemrecord,
min(case when transtype = 6001 then transdate end) as date_6001,
max(case when transtype = 6002 then transdate end) as date_6002,
datediff(day,
min(case when transtype = 6001 then transdate end),
max(case when transtype = 6002 then transdate end)
) as diff
from (select p.*,
sum(case when transtype = 6002 then 1 else 0 end) over (partition by itemrecord order by transdate desc) as grp
from project p
) p
group by itemrecord, grp;
这为每个"段提供了时间"。如果你想要总数,那么将它作为子查询/ CTE并添加另一层聚合。