2017-06-20 70 views
1

有沒有更快的方法來轉換我的數據從列a - d是人事信息,然後列e是離開開始日和列f是離開結束日期如下:水平日期間隔到垂直日期(可能是sql/vba循環解決方案?)

列a - d在每一行和列e上重複,並且在該範圍內包含的每個日期/日期是單獨一行?

目前我正在手動完成此項工作,以準備在偵察中採取/定時的大假。

我還應該補充說,每行都包含員工休假的時間間隔,同一個員工可能會在數據集中多次出現。

我正在閱讀SQL腳本,雖然它似乎沒有覆蓋這種情況,爲每個人創建了很多行和間隔。

+0

您可以將數據導入到一個無形的連接片比第二片,在您使用公式的指向正確的數據在第一頁顯示。 – Peter

+0

請顯示錶格結構/腳本和示例數據。還請顯示您嘗試過的例子。 –

回答

1

如果你想在SQL中解決這個問題,那麼你可以使用日曆或日期表來處理這類事情。

對於內存只有152KB,可以有30個年份的日期的表中的這個:

/* dates table */ 
declare @fromdate date = '20000101'; 
declare @years int = 30; 
/* 30 years, 19 used data pages ~152kb in memory, ~264kb on disk */ 
;with n as (select n from (values(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) t(n)) 
select top (datediff(day, @fromdate,dateadd(year,@years,@fromdate))) 
    [Date]=convert(date,dateadd(day,row_number() over(order by (select 1))-1,@fromdate)) 
into dbo.Dates 
from n as deka cross join n as hecto cross join n as kilo 
       cross join n as tenK cross join n as hundredK 
order by [Date]; 
create unique clustered index ix_dbo_Dates_date on dbo.Dates([Date]); 

如果不考慮創建一個表的實際步驟,你就可以使用一個日期的即席表common table expression只有這個:

declare @fromdate date, @thrudate date; 
select @fromdate = min(fromdate), @thrudate = max(thrudate) from dbo.leave; 

;with n as (select n from (values(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) t(n)) 
, dates as (
    select top (datediff(day, @fromdate, @thrudate)+1) 
     [Date]=convert(date,dateadd(day,row_number() over(order by (select 1))-1,@fromdate)) 
    from n as deka cross join n as hecto cross join n as kilo 
       cross join n as tenK cross join n as hundredK 
    order by [Date] 
) 

二者必選其一,像這樣:

/* `distinct` if there are overlaps or duplicates to remove */ 
select distinct 
    l.personid 
    , d.[Date] 
from dbo.leave l 
    inner join dates d 
    on d.date >= l.fromdate 
    and d.date <= l.thrudate; 

rextester演示:http://rextester.com/AVOIN59493

從這個測試數據:

create table leave (personid int, fromdate date, thrudate date) 
insert into leave values 
(1,'20170101','20170107') 
,(1,'20170104','20170106') -- overlapped 
,(1,'20170420','20170422') 
,(2,'20170207','20170207') -- single day 
,(2,'20170330','20170405') 

回報:

+----------+------------+ 
| personid | Date | 
+----------+------------+ 
|  1 | 2017-01-01 | 
|  1 | 2017-01-02 | 
|  1 | 2017-01-03 | 
|  1 | 2017-01-04 | 
|  1 | 2017-01-05 | 
|  1 | 2017-01-06 | 
|  1 | 2017-01-07 | 
|  1 | 2017-04-20 | 
|  1 | 2017-04-21 | 
|  1 | 2017-04-22 | 
|  2 | 2017-02-07 | 
|  2 | 2017-03-30 | 
|  2 | 2017-03-31 | 
|  2 | 2017-04-01 | 
|  2 | 2017-04-02 | 
|  2 | 2017-04-03 | 
|  2 | 2017-04-04 | 
|  2 | 2017-04-05 | 
+----------+------------+ 

數量和日曆表參考:

0

傢伙,我是如何解決這實際上是隻用在這個論壇涉及的日期間隔加入之間另一個公式。

工作很好!

Ps將日曆用於考慮週末和公衆假期的實際工作日的另一場景....

感謝