2017-04-19 133 views
-2

選擇單次入境多個值我有一個表包含以下信息通過過濾

(僱員,DriverLicenseExpiryDate,AutoInsuranceExpiryDate,TWICCardExpiryDate)

如何選擇與任何許可的員工某一天內到期(讓我們說30天)?

我想獲得這樣的

EmployeeID ExpiryDate LicenseType 

10001  2017-04-31 Driver license 
10002  2017-04-21 Driver license 
10002  2017-05-11 Auto insurance 
10003  2017-04-20 Driver license 
10003  2017-05-01 TWIC card 

因此這可能嗎? 謝謝!

+0

類似'select * from table where expirydate <= now()+ 30'只需替換爲DBMS的正確語法 –

+0

這不僅僅是選擇員工1次嗎? –

+0

它選擇所有過期日期小於+30天的僱員 –

回答

0

如果您正在使用MSSQL你必須BETWEEN運算這是完美的:

SELECT EmployeeID, DriverLicenseExpiryDate AS ExpiryDate, 'Driver License' AS LicenseType 
    FROM YourTable 
    WHERE DriverLicenseExpiryDate BETWEEN GETDATE() AND GETDATE() + 30 
UNION SELECT EmployeeID, AutoInsuranceExpiryDate AS ExpiryDate, 'Auto Insurance' AS LicenseType 
    FROM YourTable 
    WHERE AutoInsuranceExpiryDate BETWEEN GETDATE() AND GETDATE() + 30 
UNION SELECT EmployeeID, TWICCardExpiryDate AS ExpiryDate, 'TWIC Card' AS LicenseType 
    FROM YourTable 
    WHERE TWICCardExpiryDate BETWEEN GETDATE() AND GETDATE() + 30 

如果你在它允許您可以簡化這種使用變量的腳本的環境中工作的奢侈品:

DECLARE @startDate AS DATE = GETDATE(); 
DECLARE @endDate AS DATE = GETDATE() + 10; 

SELECT EmployeeID, DriverLicenseExpiryDate AS ExpiryDate, 'Driver License' AS LicenseType 
    FROM YourTable 
    WHERE DriverLicenseExpiryDate BETWEEN @startDate AND @endDate 
UNION SELECT EmployeeID, AutoInsuranceExpiryDate AS ExpiryDate, 'Auto Insurance' AS LicenseType 
    FROM YourTable 
    WHERE AutoInsuranceExpiryDate BETWEEN @startDate AND @endDate 
UNION SELECT EmployeeID, TWICCardExpiryDate AS ExpiryDate, 'TWIC Card' AS LicenseType 
    FROM YourTable 
    WHERE TWICCardExpiryDate BETWEEN @startDate AND @endDate; 
+0

這確實會選擇具有適當過濾器的所有員工,但我想爲多個許可證過期的員工設置多行,如我的帖子顯示。 –

+0

@ jchien66查看更新 – krowe

+0

呃!我正在考慮多重聯盟選擇,但認爲可能有另一種解決方案。感謝您提供詳細的解決方案! –

0

我會用outer apply unpivot的數據,然後套用conditioon:

select t.EmployeeId, v.LicenceType, v.ExpiryDate 
from t cross apply 
    (values ('Driver License', DriverLicenseExpiryDate), 
      ('Auto Insurance', AutoInsuranceExpiryDate), 
      ('TWIC Card', TWICCardExpiryDat) 
    ) v(LicenceType, ExpiryDate) 
where v.ExpiryDate >= getdate() and 
     v.ExpiryDate < dateadd(day, 30, getdate(); 

這是反轉數據的最有效方式,因爲原始表只讀取一次。另外,日期的條件僅表示一次。

我也建議仔細查看日期算術。 getdate()有一個時間組件,所以它可能不會完全按照你想要的。