2016-06-20 61 views
0

我有2個SQL表,一個用於subscribers (ID, Name),第二個爲subscribers_Upgrades [Subscriber_ID (FK), Upgrade_Level, Upgrade_Date)加入與子查詢來計算最低DATEDIFF

(有7個升級級別)

我需要一個查詢,以獲得前10名的用戶誰升級在特定Upgrade_Level最短週期和Upgrade_Level,並Upgrade Date(可用7升級水平中的任何一個),和內的特定時期

我們可以例如提供2個條件等
Where Upgrade_Level = 3 and Upgrade_Date between '01-April-2014' and '20-May-2016'

+0

您正在使用哪個數據庫管理系統? –

+0

缺省值爲SQL –

+0

「SQ」是一種查詢語言,而不是DBMS。每個關係數據庫都使用SQL作爲查詢語言。 –

回答

0

你的意思是最短的時間?誰已在upgrade_date訂單的最早時間升級?

SELECT TOP 10 s.ID, 
    s.Name, 
    su.UpgradeLevel, 
    su.UpgradeDate 
    FROM Subscribers s 
    INNER JOIN SubscribersUpgrades su on s.ID = su.SubscriberId 
    WHERE su.UpgradeLevel = 3 AND su.UpgradeDate BETWEEN '01-April-2014' AND '20-May-2016' 
    ORDER BY su.UpgradeDate ASC 

UPDATE

如果你只需要2升級級別(級別2和3)這應該工作數據 -

SELECT TOP 10 s.Name, DATEDIFF(dd,t1.UpgradeDate,t2.UpgradeDate) UpgradePeriodInDays FROM 

(SELECT su.SubscriberId, su.UpgradeDate FROM SubscribersUpgrades su 
WHERE su.UpgradeLevel = 2) t1 

INNER JOIN (SELECT su.SubscriberId, su.UpgradeDate FROM SubscribersUpgrades su 
WHERE su.UpgradeLevel = 3) t2 on t1.SubscriberId = t2.SubscriberId 

INNER JOIN Subscribers s on t1.SubscriberId = s.ID 

WHERE t2.UpgradeDate BETWEEN '01-June-2016' AND '20-July-2016' 
ORDER BY DATEDIFF(dd,t1.UpgradeDate,t2.UpgradeDate) ASC 
+0

非常感謝Nayen先生爲您做出的回覆,但我的意思是那些花時間從第二級升級到第三級的用戶(假設我們需要讓訂戶升級到第三級) 我們有時間進行每次升級在柱[Upgrade_Date]和Subscriber_ID作爲外鍵 和更準確升級水平不是int類型它們nvarchar的並且如下面恰好: 1-基本 2-預Intermidate 3- Intermidate 4-高級 5-一星高級經理 6-雙星高級經理 7-三星高級經理 –