0

我需要从涵盖 7 个月的两列中返回每日总和,但我正在尝试这样做,但这太耗时了。有没有一种方法可以按顺序返回这些,一次递增一天?

select SUM(TotalBet)SALES, SUM(TotalWin)PRIZES from play nolock where CurrentDate between '1/1/2013 07:00:00' and '1/2/2013 7:00:00'

select SUM(TotalBet)SALES, SUM(TotalWin)PRIZES from play nolock where CurrentDate between '1/2/2013 07:00:00' and '1/3/2013 7:00:00'

select SUM(TotalBet)SALES, SUM(TotalWin)PRIZES from play nolock where CurrentDate between '1/3/2013 07:00:00' and '1/4/2013 7:00:00'

select SUM(TotalBet)SALES, SUM(totalbet)PRIZES from play nolock where CurrentDate between '1/4/2013 07:00:00' and '1/5/2013 7:00:00'

select SUM(TotalBet)SALES, SUM(TotalWin)PRIZES from play nolock where CurrentDate between '1/5/2013 07:00:00' and '1/6/2013 7:00:00'

select SUM(TotalBet)SALES, SUM(TotalWin)PRIZES from play nolock where CurrentDate between '1/6/2013 07:00:00' and '1/7/2013 7:00:00'
4

3 回答 3

1

使用数字表格生成日期,然后加入表格并按天分组。您可以直接前往表格,但如果您缺少日期(例如假期),则如果没有数字表格,它们将不会显示在结果中。

SELECT 
   D.Date, SUM(TotalBet) as Sales, SUM(TotalBet) as Prizes
FROM (
   SELECT DATEADD(dd, CONVERT(datetime, '2013-01-01 07:00'), Number) as Date
   FROM dbo.NumbersTable(0, 210) --210 days
) as D
LEFT OUTER JOIN Play as P ON
   P.CurrentDate >= D.Date AND P.CurrentDate < D.Date
GROUP BY
   D.Date

您还(可能)不想使用 BETWEEN,因为您最终可能会在边界上出现重复项(BETWEEN 两边都包含)。

于 2013-07-08T14:10:44.613 回答
1

你想要一个聚合。关键是将 转换datetimedate. 要获得正确的日期,请减去 7 小时:

select cast(CurrentDate - 7.0/24 as date) as thedate,
       SUM(TotalBet) as SALES, SUM(totalbet) as PRIZES
from play nolock
group by cast(CurrentDate - 7.0/24 as date)
order by 1;
于 2013-07-08T14:11:30.603 回答
0

我不得不猜测你在追求什么,但我认为以下方法有效:

select
  AdminDate,
  SUM(TotalBet) SALES,
  SUM(totalbet) PRIZES --Unless the DB has a CS collation, this is identical to the above
from
    (select
        DATEADD(day,DATEDIFF(day,0,DATEADD(hour,-7,CurrentDate)),0) as AdminDate,
        TotalBet
    from play
    ) t
where AdminDate >= '20130101' and AdminDate < '20130801'
group by AdminDate
order by AdminDate asc

(请注意,这将无法从使用索引中受益 - 如果这很重要,请考虑将AdminDate其作为计算列添加到表中)

关键是创建此AdminDate列,它首先从 中减去 7 小时CurrentDate,然后从结果中删除时间部分 - 这意味着从今天早上 7 点到明天早上 7 点之前的每个日期时间值都将被视为管理目的发生在“今天”。一旦我们有了这些AdminDates,就很容易对它们执行 aGROUP BY以找到每个 s 的总数AdminDay


注意我也nolock从查询中删除了,因为它没有做你认为它正在做的事情。在您的原始查询中,它为play名为nolock. 如果您确实需要查询不对表执行任何锁定,则要使用WITH (NOLOCK)

于 2013-07-08T14:16:34.050 回答