我有2个SQL表,一个用于subscribers (ID, Name)
,第二个用于subscribers_Upgrades [Subscriber_ID (FK), Upgrade_Level, Upgrade_Date)
(有7个升级级别)
我需要一个查询来获取在最短时间段内升级的前10位订阅者Upgrade_Level
和Upgrade Date
针对特定Upgrade_Level
(任何一种可用的7升级级别),并在特定的时间内
我们可以,例如提供像2B这样的2个条件
Where Upgrade_Level = 3 and Upgrade_Date between '01-April-2014' and '20-May-2016'
答案 0 :(得分: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
<强>更新强>
如果您只需要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