SQL Query列出最近7天的记录

时间:2015-01-12 19:25:21

标签: sql sql-server select

我需要查询列出日期的所有记录,如果记录不存在则查询应该列出0

SELECT  Count(C.ConversionStatusID) Visits, CONVERT(VARCHAR(10),ActionDate,110) ActionDate
FROM Conversion C
WHERE C.ConversionStatusID = 2 AND 
      ActionDate Between DateAdd(day,-7,GetDate()) AND GETDATE()
GROUP BY CONVERT(VARCHAR(10),ActionDate,110) 
Order BY CONVERT(VARCHAR(10),ActionDate,110) DESC

预期输出应始终产生7条记录,样本结果应如下

  ActionDate    Visits
  01-09-2015    1
  01-08-2015    5
  01-07-2015    0
  01-06-2015    0
  01-05-2015    3
  01-04-2015    8
  01-03-2015    0

提前致谢

2 个答案:

答案 0 :(得分:0)

您需要拥有过去7天的日期表,然后您可以left join

with cte (value, n)
as
(
  select DATEADD(DAY, DATEDIFF(day,0,getdate()),0) as value,1 as n
  UNION ALL
  SELECT DATEADD(day, -1, value) as value, n+1
  from cte
  where n < 7
)
select CONVERT(VARCHAR(10),cte.value,110) as ActionDate ,  Count(C.ConversionStatusID) Visits
from cte
left join Conversion C
ON CONVERT(VARCHAR(10),C.ActionDate,110) = CONVERT(VARCHAR(10),cte.value,110)
and  C.ConversionStatusID = 2
GROUP BY CONVERT(VARCHAR(10),cte.value,110) 
Order BY CONVERT(VARCHAR(10),cte.value,110) DESC

答案 1 :(得分:0)

这样的事情会起作用,但是你将不得不玩弄什么应该是约会,什么应该是约会时间。您根本不清楚何时何地需要时间组件。特别是,您的WHERE子句似乎与查询的其余部分相矛盾,因为它不会剥夺时间。例如,如果GETDATE()是1月12日下午2点,那么是1月11日下午1点或者前一天下午1点?那么1月5日下午1点呢,因为WHERE条款正在剥离它。

如果日期是00:00到23:59(尽管WHERE子句仍然关闭):

;WITH Dates ([Date]) AS (
    SELECT CAST(DATEADD(DAY,-1,GETDATE()) AS DATE) UNION
    SELECT CAST(DATEADD(DAY,-2,GETDATE()) AS DATE) UNION
    SELECT CAST(DATEADD(DAY,-3,GETDATE()) AS DATE) UNION
    SELECT CAST(DATEADD(DAY,-4,GETDATE()) AS DATE) UNION
    SELECT CAST(DATEADD(DAY,-5,GETDATE()) AS DATE) UNION
    SELECT CAST(DATEADD(DAY,-6,GETDATE()) AS DATE) UNION
    SELECT CAST(DATEADD(DAY,-7,GETDATE()) AS DATE))
SELECT  D.Date,
    COALESCE(Count(C.ConversionStatusID),0) Visits
FROM Dates D
LEFT JOIN Conversion C
    ON D.[Date] = CAST(C.ActionDate AS Date)
WHERE C.ConversionStatusID = 2 AND 
      ActionDate Between DateAdd(day,-7,GetDate()) AND GETDATE()
GROUP BY CONVERT(VARCHAR(10),ActionDate,110) 
Order BY CONVERT(VARCHAR(10),ActionDate,110) DESC

如果你有一个数字或计数表,你可以不使用CTE,但是对于这么小的东西,它确实赢得了那么多。