2012-11-09 148 views
0

我使用h2數據庫。 我有3個表:USER,SCHEDULEWORKER和SECURITYACCESS。查詢選擇時間戳字段

用戶

userNumber, firstName, lastName 

SCHEDULEWORKER

USERNUMBER, STARTDATE, ENDDATE 

SECURITYACCESS

USERNUMBER, DATEACCESS, DOOR 

STARTDATE, ENDDATE and DATEACCESS使用時間戳datatype

我想知道所有用戶誰假設一天工作,誰開始日期後進入maindoor。

所以在這個例子中

SCHEDULEWORKER 
USERNUMBER  STARTDATE    ENDDATE 
4141   2012-07-02 07:30:00.0 2012-07-02 16:30:00.0 
4123   2012-07-02 07:30:00.0 2012-07-02 16:30:00.0 

SECURITYACCESS 
USERNUMBER  DATEACCESS  DOOR 
4145 2012-07-02 07:31:56.0 MainDoor 
4123 2012-07-02 07:29:56.0 MainDoor 

我想有

USERNUMBER STARTDATE    ENDDATE    DATEACCESS  DOOR  late 
4141 2012-07-02 07:30:00.0 2012-07-02 16:30:00.0 2012-07-02 07:31:56.0 MainDoor 00:01:56 

我需要拆分我場時間戳是能夠做到這一點查詢?

+0

什麼是一天的工作意味着什麼?工作一整天?在當前工作?從7:30到15:30或在不同的時間工作? – sufleR

+0

每天工作意味着有開始日期和結束日期的值 – redfox26

+0

它可以像'SCHEDULEWORKER s,SECURITYACCESS a where s.USERNUMBER = a.USERNUMBER和s.STARTDATE> a.DATEACCESS'一樣簡單嗎? –

回答

2

它會很慢,但如果你在一天有很多SECURITYACESS,你必須比較當天的第一次訪問。 所以你必須要管理時間戳計算逾期列

select SW.USERNUMBER, STARTDATE, ENDDATE, DATEACCESS, DOOR, (h2 calculations on timestamps) as late 
FROM SCHEDULEWORKER AS SW 
    inner join SECURITYACCESS AS SA on SW.USERNUMBER=SA.USERNUMBER 
    inner join (SELECT USERNUMBER, MIN(DATEACCESS) as ACCESS 
       FROM SECURITYACCESS 
       GROUP BY USERNUMBER, YEAR(DATEACCESS), DAY_OF_YEAR(DATEACCESS)) AS MSA ON SW.USERNUMBER = MSA.USERNUMBER AND MSA.ACCESS = SA.DATEACCESS 
WHERE SW.STARTDATE < MSA.ACCESS 

如果您有更多的有條件的地方我不H2工作:日期範圍可能或usernumber作爲參數,你應該改變MSA查詢更好的性能。

我沒有找到時間戳到日期轉換或功能更好的分組。

+0

稍作修改,不包括h2計算爲遲...選擇SW.USERNUMBER,STARTDATE,ENDDATE,DATEACCESS, DOOR FROM SCHEDULEWORKER AS SW 內部連接SECURITYACCESS AS SA上的SW.USERNUMBER = SA.USERNUMBER 內部連接(SELECT USERNUMBER,MIN(DATEACCESS)as ACCESS FROM SECURITYACCESS GROUP BY USERNUMBER,YEAR(DATEACCESS),DAY_OF_YEAR(DATEACCESS))AS MSA ON SW.USERNUMBER = MSA.USERNUMBER AND MSA.ACCESS = SA.DATEACCESS WHERE DATEDIFF(day,SW.STARTDATE,MSA.ACCESS)= 0 和SW.STARTDATE> MSA.ACCESS – redfox26