按ID分组的SQL Select Day IN和Day OUT

时间:2018-09-24 23:42:08

标签: sql sql-server

如何按日期将2014年1月15日至2014年3月18日之间的EID分组

| ID |EID  |      DATE    |  Status |     |
|----------|--------------|---------|-----|
|  9 |9991 | 2014-03-16   |     OUT |     |
|  8 |9997 | 2014-03-18   |     IN  |     |
|  7 |9997 | 2014-03-16   |     OUT |     |
|  6 |9999 | 2014-02-16   |     IN  |     |
|  5 |9999 | 2014-02-16   |     OUT |     |
|  4 |9996 | 2014-03-18   |     IN  |     |
|  3 |9996 | 2014-03-16   |     OUT |     |
|  2 |9997 | 2014-01-18   |     IN  |     |
|  1 |9997 | 2014-01-15   |     OUT |     |

输出应类似于:

|  
|EID   |in date       |   OUT date|  DAYS OUT |  
|------|--------------|---------  |------ ----|
| 9997 | 2014-03-18   | 2014-03-16|      2    |
| 9997 | 2014-01-18   | 2014-01-15|      3    |
| 9999 | 2014-02-16   | 2014-02-16|      0    |
| 9996 | 2014-03-18   | 2014-03-16|      2    |
| 9991 |              | 2014-03-16|           |

谢谢

2 个答案:

答案 0 :(得分:0)

这里是一种假设它们是交错的方法,因此不会有两个来龙去脉

select eid,
       max(case when status = 'in' then date end) as in_date,
       max(case when status = 'out' then date end) as out_date,
       datediff(day,
                max(case when status = 'in' then date end),
                max(case when status = 'out' then date end)
               ) as days_diff
from (select t.*, row_number() over (partition by eid, status order by date) as seqnum
      from t
     ) t
group by eid, seqnum;

答案 1 :(得分:-2)

我认为您已经做到了,但是,您是否尝试过这样的句子:

从[您的表格]中选择[您希望在此处格式化的格式]在“ 2014-01-15”和“ 2014-03-18”之间按日期分组的日期

从[您的表]中选择[在这里按您希望的格式设置] WHERE dateIn> ='2014-01-15'AND dateOut <='2014-03-18'GROUP BY dateIn

可以分享您的整个桌子吗?