如何通过一系列日期获得价值?

时间:2016-04-12 11:00:43

标签: sql sql-server sql-server-2014

我有一张像这样的桌子

enter image description here

使用此代码,我获得每个domainId的5个最新值

  ;WITH grp AS 
(
   SELECT DomainId, [Date],Passed, DatabasePerformance,ServerPerformance, 
     rn = ROW_NUMBER() OVER
     (PARTITION BY DomainId ORDER BY [Date] DESC)
   FROM dbo.DomainDetailDataHistory H
)
  SELECT g.DomainId, g.[Date],g.Passed, g.ServerPerformance, g.DatabasePerformance
  FROM grp g
  INNER JOIN @Latest T ON T.DomainId = g.DomainId 
  WHERE rn < 7 AND t.date != g.[Date]
  ORDER BY DomainId, [Date] DESC

我想要什么

嗯,我想知道这5个最新行中每一行的售票数量,但条件如下:

这些行中的每一行都有自己的日期,这些日期不同。 对于每个日期,我想查看过去15分钟内售出的数量以及过去30分钟售出的数量。

示例:

我为每个domainId获得了这5行

enter image description here

我想用两列扩展上述内容,“soldTicketsLast15”和“soldTicketsLast30”

日期列包含我需要的所有日期,并且对于每个日期我想要返回15分钟并返回30分钟并获得售出的票数

示例:

SELECT MAX(SoldTickets) FROM DomainDetailDataHistory
WHERE [Date] >= DATEADD(minute, -15, '2016-04-12 12:10:28.2270000')

SELECT MAX(SoldTickets) FROM DomainDetailDataHistory
WHERE [Date] >= DATEADD(minute, -30, '2016-04-12 12:10:28.2270000')

我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:1)

我会使用OUTER APPLY or CROSS APPLY

;WITH grp AS 
(
    SELECT 
        DomainId, [Date], Passed, DatabasePerformance, ServerPerformance, 
        rn = ROW_NUMBER() OVER (PARTITION BY DomainId ORDER BY [Date] DESC)
    FROM dbo.DomainDetailDataHistory H
)
SELECT
    g.DomainId, g.[Date],g.Passed, g.ServerPerformance, g.DatabasePerformance
    ,A15.SoldTicketsLast15
    ,A30.SoldTicketsLast30
FROM
    grp g
    INNER JOIN @Latest T ON T.DomainId = g.DomainId
    OUTER APPLY
    (
        SELECT MAX(H.SoldTickets) - MIN(H.SoldTickets) AS SoldTicketsLast15
        FROM DomainDetailDataHistory AS H
        WHERE
            H.DomainId = g.DomainId AND
            H.[Date] >= DATEADD(minute, -15, g.[Date])
    ) AS A15
    OUTER APPLY
    (
        SELECT MAX(H.SoldTickets) - MIN(H.SoldTickets) AS SoldTicketsLast30
        FROM DomainDetailDataHistory AS H
        WHERE
            H.DomainId = g.DomainId AND
            H.[Date] >= DATEADD(minute, -30, g.[Date])
    ) AS A30
WHERE
    rn < 7
    AND T.[date] != g.[Date]
ORDER BY DomainId, [Date] DESC;

要使相关的APPLY查询有效,应该有适当的索引,如下所示:

CREATE NONCLUSTERED INDEX [IX_DomainId_Date] ON [dbo].[DomainDetailDataHistory]
(
    [DomainId] ASC,
    [Date] ASC
)
INCLUDE ([SoldTickets])

此索引还可以帮助您使查询的主要部分(grp)有效。

答案 1 :(得分:-1)

如果我正确理解了您的问题,您希望从您的某个日期(在“日期”列中)销售的票可以追溯到15分30分钟。假设您正在使用DATEADD函数,则以下内容应该起作用:

SELECT MAX(SoldTickets) FROM DomainDetailDataHistory
WHERE [Date] BETWEEN [DATE] AND DATEADD(minute, -15, '2016-04-12 12:10:28.2270000') GROUP BY [SoldTickets]

between运算符允许您检索两个日期参数之间的结果。在上面的SQL中,我们还需要一个组,因为您使用的是GROUPING函数(MAX)。小组依赖于你想要分组的内容,但我认为在你的情况下它将是SoldTickets。

上面的SQL将为您提供日期和15分钟之间的SQL。 30分钟后你可以做类似的事情。