如何在SQL Server中从今天开始获取前7天的数据

时间:2018-10-05 12:24:29

标签: sql sql-server datetime

我有一个名为GuestAddressData(UserId INT, EDate DateTime)的DataEntry表,其中包含用户数据。我需要获取今天到之前7天的用户数量。我的查询:

SELECT 
  row_number() over (order by (SELECT 1)) ID,
  count(*) Total,
  LEFT(Datename(weekday, Cast(EDate as date)), 3) Day
FROM 
  CRM0001GuestAddressData
WHERE
  EDate >= dateadd(week, datediff(d, -1, getdate()-2)/7, -1)
GROUP BY
  Cast(EDate as date)
ORDER BY
  Cast(EDate as date)

例如,如果今天是星期五,那么我的预期输出是:

ID   |   TOTAL  |   DAY
------------------------
1    |    78    |   Sat
2    |    23    |   Sun
3    |    54    |   Mon
4    |    17    |   Tues
5    |    56    |   Wed
6    |    45    |   Thus
7    |    78    |   Fri  -  Today

但这是不正确的。如何解决?

2 个答案:

答案 0 :(得分:1)

SELECT 
  row_number() over (order by dDate) ID,
  cnt,
  LEFT(Datename(weekday, dDate), 3) Day
from
(Select cast(EDate as Date) as dDate,
       count(*) as cnt
FROM (values (0),(1),(2),(3),(4),(5),(6)) t(v)
  inner join
  CRM0001GuestAddressData gd on datediff(d, gd.Edate, getdate()) = t.v 
WHERE
  EDate >= dateadd(d, -6, cast(getdate() as date)) and EDate < dateadd(d,1,cast(getdate() as date))
GROUP BY
  Cast(EDate as date)) tmp;

注意:您打算从昨天起7天,对吗?没关系,请根据您的样品进行纠正。

DBFiddle demo

编辑:全天候

SELECT 
  row_number() over (order by dDate) ID,
  cnt,
  LEFT(Datename(weekday, dDate), 3) Day
from
(Select dateadd(d,-v,cast(getdate() as date)) as dDate,
       count(Edate) as cnt
FROM (values (0),(1),(2),(3),(4),(5),(6)) t(v)
  left join
  CRM0001GuestAddressData gd on Datediff(d,gd.EDate, getdate()) = t.v 
GROUP BY
  dateadd(d,-v,cast(getdate() as date))) tmp;

DBFiddle Demo

答案 1 :(得分:1)

您可以“生成”七个数字的列表,并用它来构建所需的日期。然后左键连接数据以获取计数,包括零:

WITH datelist(num, a, b) AS (
    SELECT num, DATEADD(DAY, -num, CAST(CURRENT_TIMESTAMP AS DATE)), DATEADD(DAY, -num + 1, CAST(CURRENT_TIMESTAMP AS DATE))
    FROM (VALUES (0), (1), (2), (3), (4), (5), (6)) AS v(num)
)
SELECT 7 - num AS ID, datelist.a AS Day, COUNT(IDBooking)
FROM datelist
LEFT JOIN T_Bookings ON Opened >= datelist.a AND Opened < datelist.b
GROUP BY datelist.a, datelist.num
ORDER BY datelist.a