在我的存储过程中,我返回按日期分组的总分钟数。日期范围是从昨天开始的一周。程序运行正常。但是,我面临的一个问题是。并不总是在7天之间会有特定日期的任何数据。
例如,如果我今天运行我的程序,它会返回此信息。
**Min Date**
47 2014-08-03
153 2014-08-04
45 2014-08-05
166 2014-08-06
这位特殊的人在8月31日,8月1日和2日没有任何数据。因此,存储过程不会返回任何数据。
我想要做的是在数据库中没有记录的日子返回0。
**Min Date**
0 2014-07-31
0 2014-08-01
0 2014-08-02
47 2014-08-03
153 2014-08-04
45 2014-08-05
166 2014-08-06
这是程序:
ALTER PROCEDURE [dbo].[getAgentChartData]
(
@ABID BIGINT
)
AS
BEGIN
SET NOCOUNT ON;
--RETURNING 7 DAYS WORTH OF DATA FROM YESTERDAY
DECLARE @TODAY AS DATE =GETDATE(),@WEEK AS DATE
SET @WEEK = DATEADD (DD, -8, @TODAY)
SELECT SUM(MINUTES) AS TOTALMINUTES, CONVERT(DATE, STARTDATE) AS DATE FROM PoLines
WHERE ADDRESSBOOKID = @ABID AND STARTDATE BETWEEN @WEEK AND @TODAY
GROUP BY CONVERT(DATE, STARTDATE)
END
有什么建议吗?
编辑*
添加了霍根的建议。仍然遇到问题。
WITH Dates AS
(
SELECT DATEADD (DD, -7, GETDATE()) AS DAY
UNION ALL
SELECT DATEADD (DD, -6, GETDATE()) AS DAY
UNION ALL
SELECT DATEADD (DD, -5, GETDATE()) AS DAY
UNION ALL
SELECT DATEADD (DD, -4, GETDATE()) AS DAY
UNION ALL
SELECT DATEADD (DD, -3, GETDATE()) AS DAY
UNION ALL
SELECT DATEADD (DD, -2, GETDATE()) AS DAY
UNION ALL
SELECT DATEADD (DD, -1, GETDATE()) AS DAY
)
SELECT SUM(MINUTES) AS TOTALMINUTES, CONVERT(DATE, Dates.Day) AS DATE
FROM Dates
LEFT JOIN PoLines ON CONVERT(DATE, STARTDATE) = CONVERT(DATE, Dates.Day)
WHERE ADDRESSBOOKID = @ABID
GROUP BY CONVERT(DATE, Dates.Day)
答案 0 :(得分:2)
在这样的小案例中,我只使用CTE制作内联表。像这样:
WITH Dates AS
(
SELECT DATEADD (DD, -8, GETDATE()) AS DAY
UNION ALL
SELECT DATEADD (DD, -7, GETDATE()) AS DAY
UNION ALL
SELECT DATEADD (DD, -6, GETDATE()) AS DAY
UNION ALL
SELECT DATEADD (DD, -5, GETDATE()) AS DAY
UNION ALL
SELECT DATEADD (DD, -4, GETDATE()) AS DAY
UNION ALL
SELECT DATEADD (DD, -3, GETDATE()) AS DAY
UNION ALL
SELECT DATEADD (DD, -2, GETDATE()) AS DAY
UNION ALL
SELECT DATEADD (DD, -1, GETDATE()) AS DAY
)
SELECT SUM(ISNULL(MINUTES,0)) AS TOTALMINUTES, CONVERT(DATE, Dates.Day) AS DATE
FROM Dates
LEFT JOIN PoLines ON CONVERT(DATE, STARTDATE) = CONVERT(DATE, Dates.Day)
AND ADDRESSBOOKID = @ABID
GROUP BY CONVERT(DATE, Dates.Day)
因为您将从Dates表中继续加入,所以您将获得Dates表的所有元素以及PoLines表的所有元素。然后group by将最多滚动7行。
您还可以在数据库中设置日期表以加入,并使用where子句限制日期范围(这是标准做法。)
注意,我现在无权访问数据库,所以我没有测试它可能有错字的SQL。